<?php

/**
 * 合同service
 * @author wangwx 2015-5-7
 */

namespace common\services\myhtsq;

use common\entities\common\MyscrmContractEntity;
use common\entities\myhtsq\ContractApplicationEntity;
use common\entities\myhtsq\ContractBusinessTypeEntity;
use common\entities\myhtsq\ContractDocumentEntity;
use common\entities\myhtsq\ContractPaymentEntity;
use common\entities\myhtsq\ContractProductEntity;
use common\entities\myhtsq\ContractRevenueEntity;
use common\entities\myhtsq\ContractShipmentEntity;
use common\entities\myhtsq\ContractSupplierEntity;
use common\entities\myhtsq\ContractBackAmountEntity;
use common\entities\myhtsq\DocumentEntity;
use common\models\myhtsq\ContractReceivableModel;
use common\repositories\myhtsq\ContractBusinessTypeRepository;
use common\repositories\myhtsq\ContractEmailContactsRepository;
use common\repositories\myhtsq\ContractSupplierRepository;
use common\repositories\myhtsq\ContractSuppliersPaymentRepository;
use common\repositories\myhtsq\IncomeItemLogRepository;
use common\repositories\myhtsq\InvoiceBusinessUnitRepository;
use common\repositories\myhtsq\InvoiceReceivableRepository;
use common\services\BaseService;
use common\error\ErrorCode;
use common\models\myhtsq\ContractManageModel;
use common\entities\ConfigEntity;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ContractApplicationRepository;
use common\entities\myhtsq\ContractManageEntity;
use common\entities\myhtsq\ApplicationBalanceRateEntity;
use common\entities\myhtsq\ContractPayoverEntity;
use common\repositories\myhtsq\ContractRevenueRepository;
use common\repositories\myhtsq\ContractRevenueCarryoverRepository;
use common\entities\myhtsq\ContractRevenueCarryoverEntity;
use common\repositories\common\MyscrmContractRepository;
use common\models\myhtsq\ContractRevenueModel;
use common\repositories\myhtsq\InvoiceRepository;
use common\repositories\myhtsq\ContractPaymentRepository;
use common\repositories\common\MyscrmOrganizationRepository;
use common\repositories\common\OrganizationToAuthorizeRepository;
use common\repositories\common\MyscrmApplicationRepository;
use common\repositories\myhtsq\SpecialApprovalAuthorizeRepository;
use common\repositories\myhtsq\ContractPropertyRepository;
use common\repositories\myhtsq\ContractCategoryRepository;
use common\repositories\myhtsq\ContractBigCategoryRepository;
use common\repositories\myhtsq\ContractLittlerCategoryRepository;
use common\repositories\myhtsq\ApplicationInfoRepository;
use common\repositories\myhtsq\ReceivableItemRepository;
use common\repositories\myhtsq\MoneyCategoryItemRepository;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\repositories\myhtsq\BussAccountTypesRepository;
use common\repositories\myhtsq\ContractPayoverRepository;
use common\repositories\myhtsq\ContractBackAmountRepository;
use common\services\common\EmailService;
use common\services\common\TenantService;
use common\support\DateTimeHelper;
use common\support\Helper;
use common\support\PageParam;
use common\repositories\myhtsq\ErpUserRepository;
use common\repositories\myhtsq\DocumentRepository;
use common\repositories\myhtsq\ContractDocumentRepository;
use common\models\myhtsq\DocumentModel;
use common\models\myhtsq\ContractDocumentModel;
use common\repositories\myhtsq\SignAchievementRepository;
use common\repositories\myhtsq\PaymentAchievementRepository;
use common\repositories\myhtsq\ApplicationPriceRepository;
use common\models\myhtsq\SignAchievementModel;
use common\models\myhtsq\PaymentAchievementModel;
use common\repositories\myhtsq\ContractFlowCodeRepository;
use common\entities\myhtsq\ContractPropertyEntity;
use common\repositories\myhtsq\ContractReceivableRepository;
use common\support\ExcelManage;
use common\repositories\myhtsq\ContractAccountCompanyRepository;
use common\repositories\myhtsq\ContractCompanyRepository;
use common\repositories\myhtsq\ContractPayinfoRepository;
use common\repositories\myhtsq\InvoicePaymentRepository;
use common\repositories\myhtsq\ContractProductRepository;
use common\repositories\myhtsq\ContractShipmentRepository;
use common\support\CacheManage;
use common\support\LogHelper;
use common\support\OSS;
use common\services\myhtsq\ErpInterfaceService;
use common\entities\myhtsq\ActionCode;
use common\entities\myhtsq\RoleCode;
use common\entities\myhtsq\myscrm_contract_product;
use common\entities\myhtsq\ContractSuppliersPaymentEntity;
use common\entities\myhtsq\ContractTenantRelationEntity;
use common\entities\myhtsq\ApplicationBuRateEntity;
use common\support\StringHelper;
use PHPExcel_Shared_Date;
use Yii;
use yii\base\Exception;
use yii\web\User;

class ContractService extends BaseService
{
    public $_errorLog;
    private static $sheetIndex = 0;
    public $_contractReceivableService;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $config = [
            'logFile' => \Yii::$app->getRuntimePath() . '/logs/base/contract.log', // 日志文件路径配置
        ];
        $this->_errorLog = new LogHelper($config);
        $this->_contractReceivableService = new ContractReceivableService();
    }

    /**
     * 新建合同
     * @param array $contract 合同基本信息数组
     * @param array $productArr 产品列表数组
     * @param bool $isComeFromBusinessSystem
     * @return bool|int
     * @throws \yii\db\Exception
     */
    public function addContract($contract, $productArr, $isComeFromBusinessSystem = false, $addition = [])
    {
        $myscrmContractManageModel = new ContractManageModel();
        $myscrmContractManageModel->setScenario('add');
        $db = ConfigEntity::getDb();
        $trans = $db->beginTransaction(); //开启事务
        $myscrmContractManageModel->load($contract, '');
        try {
            if ($myscrmContractManageModel->validate()) {
                //保存时生成合同规则
                $myscrmContractManageModel->contract_code = ContractFlowCodeRepository::getContractCode();
                $myscrmContractManageModel->business_type_id='f85b3855-54ca-11e7-9f96-000c29310f8b';

                if ($isComeFromBusinessSystem) {
                    //2017.8.2新增字段
                    $myscrmContractManageModel->contract_property_id = ContractPropertyRepository::getPropertyIdByName($contract['contract_nature']);

                    $myscrmContractManageModel->company_id = ContractCompanyRepository::getContractIdByName($contract['sign_buname']);

                    $myscrmContractManageModel->input_date = $contract['contract_entry_date'];

                    $myscrmContractManageModel->effect_date = $contract['contract_effective_date'];

                    $myscrmContractManageModel->rent_amount = $contract['rentdeal_price'];

                    $myscrmContractManageModel->delivery_amount = $contract['deliverdeal_price'];

                    $myscrmContractManageModel->balance_should_amount = $contract['js_amount'];

                    $myscrmContractManageModel->contract_status = 2;
                } else {
                    //合同录入时间
                    $myscrmContractManageModel->input_date = date("Y-m-d H:i:s", ConfigEntity::getDbNowTimestamp());
                }

                //合同产品成交总额  = 租用金额
                $myscrmContractManageModel->application_deal_amount = empty($myscrmContractManageModel->rent_amount)?0:$myscrmContractManageModel->rent_amount;

                //处理 合同产品标准总额 = 合同产品标准金额（合同产品标准金额合计）
                $application_amount = 0; //合同产品标准总额 默认值
                if (!empty($productArr) && is_array($productArr)) {
                    foreach ($productArr as $value) {
                        $application_amount = $application_amount + $value['amount'];
                    }
                }

                if ($application_amount == 0) {
                    $myscrmContractManageModel->application_deal_discount = 0;
                    $myscrmContractManageModel->contract_deal_discount = 0;
                } else {
                    $myscrmContractManageModel->application_deal_discount = sprintf("%.2f", $myscrmContractManageModel->application_deal_amount / $application_amount); //产品成交折扣=合同产品成交总额/合同产品标准金额
                    $myscrmContractManageModel->contract_deal_discount = sprintf("%.2f", $myscrmContractManageModel->sign_amount / $application_amount);   //合同成交折扣=签约金额/合同产品标准总额
                }
                $myscrmContractManageModel->application_amount = $application_amount; //合同产品标准总额

                $contractManageRepository = new ContractManageRepository();

                $contractId = $contractManageRepository->saveContract($myscrmContractManageModel, $isComeFromBusinessSystem, $addition); //保存合同基本信息
                if (empty($contractId)) {
                    $trans->rollBack();

                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同失败');
                }

                ContractApplicationRepository::handleApplicationData($contractId, $productArr); //处理签约产品数据
                ContractFlowCodeRepository::addContractFlowCode($contractId); //新增合同流水表
                //处理签约业绩
                //SignAchievementRepository::handleContractSignAchievement('add', $contractId, $myscrmContractManageModel->contract_property_id, $myscrmContractManageModel->area_id, $myscrmContractManageModel->sign_people_id, $myscrmContractManageModel->income_amount);

                $trans->commit();

                return $contractId;
            } else {
                $trans->rollBack();

                return $this->setAndReturn(ErrorCode::ERR_CONTRACT_PARAM_INVALID, '', $myscrmContractManageModel->getAllFirstErrorMessage());
            }
        } catch (\Exception $e) {
            $trans->rollBack();

            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '增加合同出错' . $e->getMessage());
        }
    }

    /**
     * 更新合同
     * @param array $contract 合同基本信息数组
     * @param array $productArr 产品列表数组
     * @return boolean|integer
     */
    public function updateContract($contract, $productArr, $addition = [])
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contract['contract_id']); //获取model
        if (empty($contractModel)) {//合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }

        if ($contractModel->contract_status == ContractManageEntity::APPROVE_STATUS_PASS || $contractModel->contract_status == ContractManageEntity::APPROVE_STATUS_SUBMIT_HANDLE) {//已审核或已提交复核合同不能修改
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_APPROVE_STATUS);
        }

        $myscrmContractManageModel = new ContractManageModel();
        $myscrmContractManageModel->setScenario('update');
        $myscrmContractManageModel->load($contract, '');
        $db = ConfigEntity::getDb();
        $trans = $db->beginTransaction(); //开启事务
        try {
            if ($myscrmContractManageModel->validate()) {

                //合同产品成交总额  = 租用金额
                $myscrmContractManageModel->application_deal_amount = $myscrmContractManageModel->rent_amount;

                //处理 合同产品标准总额 = 合同产品标准金额（合同产品标准金额合计）
                $application_amount = 0; //合同产品标准总额 默认值
                if (!empty($productArr) && is_array($productArr)) {
                    foreach ($productArr as $value) {
                        $application_amount = $application_amount + $value['amount'];
                    }
                }

                $myscrmContractManageModel->application_amount = $application_amount; //合同产品标准总额
                if ($application_amount == 0) {
                    $myscrmContractManageModel->application_deal_discount = 0;
                    $myscrmContractManageModel->contract_deal_discount = 0;
                } else {
                    $myscrmContractManageModel->application_deal_discount = sprintf("%.2f", $myscrmContractManageModel->application_deal_amount / $application_amount); //产品成交折扣=合同产品成交总额/合同产品标准金额
                    $myscrmContractManageModel->contract_deal_discount = sprintf("%.2f", $myscrmContractManageModel->sign_amount / $application_amount);   //合同成交折扣=签约金额/合同产品标准总额
                }

                //合同录入时间
                if (empty($myscrmContractManageModel->input_date)) {
                    $myscrmContractManageModel->input_date = date("Y-m-d H:i:s", ConfigEntity::getDbNowTimestamp());
                }

                $contractId = ContractManageRepository::updateContract($myscrmContractManageModel, $addition);

                //更新收入项编码（收入合同号）
                ContractRevenueRepository::updateIncomeCodeByContractId($contractId, $myscrmContractManageModel->contract_code);

                //处理签约业绩
                SignAchievementRepository::handleContractSignAchievement('update', $contractId, $myscrmContractManageModel->contract_property_id, $myscrmContractManageModel->area_id, $myscrmContractManageModel->sign_people_id);

                if ($contractId === false) {//更新失败
                    $trans->rollBack();

                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_UPDATE);
                }
                ContractApplicationRepository::handleApplicationData($contractId, $productArr); // 处理签约产品数据
                $trans->commit();

                return $contractId;
            } else {
                $trans->rollBack();

                return $this->setAndReturn(ErrorCode::ERR_CONTRACT_PARAM_INVALID);
            }
        } catch (\Exception $e) {
            $trans->rollBack();

            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_UPDATE, '', '更新合同出错' . $e->getMessage());
        }
    }

    /**
     * 获取合同基本信息
     * @param string $contractId 合同id
     * @param        array
     */
    public function getContractInfo($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); //获取model
        if (empty($contractModel)) {//合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }

        $data['contract'] = $contractModel->attributes;
        $data['contract']['business_type'] = ContractBusinessTypeRepository::getBusinessTypeById($data['contract']['business_type_id'])['business_type_name'];
        $data['contract']['business_product'] = empty($data['contract']['business_type']) ? '' : \Yii::$app->params['business_product_type'][$data['contract']['business_type']];

        $data['contract']['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($contractModel->area_id); //区域名称
        $data['contract']['area_code'] = ErpBusinessUnitRepository::getBuCodeByBuguid($contractModel->area_id); //区域code
        $data['contract']['sign_people_name'] = ErpUserRepository::getUserNameByBuguid($contractModel->sign_people_id); //签约人名称
        if(empty($data['contract']['sign_people_name'])){
            $data['contract']['sign_people_name'] = $contractModel->sign_people_name;
        }
        $data['contract']['sign_people_department_name'] = ErpBusinessUnitRepository::getBunameByBuguid($contractModel->sign_people_department_id); //签约人部门名称
        $data['contract']['company_name'] = ContractCompanyRepository::getContractCompanyNameByCompanyId($contractModel->company_id); //签署公司名称
        $data['contract']['balance_rate_percent'] = ((empty($contractModel->balance_rate)?0:$contractModel->balance_rate)*100).'%';
        //获取租期
        $contract_repository = new MyscrmContractRepository();
        $contractInfo = $contract_repository->getContractByContractNum($contractModel->contract_code); //获取合同表信息

        if (empty($contractInfo)) {
            $data['contract']['beginOn'] = '';
            $data['contract']['endOn'] = '';
        } else {
            $data['contract']['beginOn'] = $contractInfo->BeginOn;
            $data['contract']['endOn'] = $contractInfo->EndOn;
        }

        $data['contract']['littler_category_name'] = ContractLittlerCategoryRepository::getContractLittlerCategoryNameByLittlerCategoryId($contractModel->littler_category_id); //获取小类名称
        //amount
        $applicationData = ContractApplicationRepository::getAllContractApplicationByContractId($contractId);
        $data['payover'] = ContractPayoverRepository::getContractPayoverInfoByContractId($contractId);

        if (!empty($data['payover'])) {
            array_walk($data['payover'], function(&$v, $k, $p) { $v = array_merge($v, $p); }, array('supplier_name' =>$data['contract']['supplier_name']));
        }

        $data['shipment'] = ContractShipmentRepository::getContractShipmentInfoByContractId($contractId);
        $data['tenant'] = $this->getTenantInfoByCode($data['contract']['contract_code']);
        $data['application'] = $this->getShareAmount($data['contract']['application_amount'], $data['contract']['rent_amount'],$data['contract']['sign_amount'],$data['contract']['area_id'],$applicationData);
        $data['products'] = ContractProductRepository::getProductByContractId($contractId);
        $data['backamountlist'] = ContractBackAmountRepository::getBackAmountListByContractid($contractId);
        if($data['contract']['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b'){
            if(!empty($data['contract']['link_contract_id'])) {
                //供应商移动工程协同合同需要获取链接合同信息
                $linkcon = ContractManageRepository::getContractManageModelByContractId($data['contract']['link_contract_id']);
                $data['linkcontract'] = $linkcon;
                $data['linkcontractother']['sign_people_name'] = ErpUserRepository::getUserNameByBuguid($data['linkcontract']['sign_people_id']); //签约人名称
                $data['linkcontractother']['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($data['linkcontract']['area_id']); //区域名称
                $data['linkcontractother']['sign_people_department_name'] = ErpBusinessUnitRepository::getBunameByBuguid($data['linkcontract']['sign_people_department_id']); //签约人部门名称
                $data['linkcontractrelation'] = ContractTenantRelationEntity::find()->where("tenant_id='" . $data['contract']['link_customer_code'] . "'")->one();
            }else {
                $this->loadSpecialData($data['contract']['customer_name'], $data);
            }
        }
        //saas合同需要获取授权产品的使用情况
        //if($data['contract']['business_type_id'] == 'f85b3855-54ca-11e7-9f96-000c29310f8b'){
            $erpinterface = new ErpInterfaceService();
            $authdata  = $erpinterface->getAuthAppUseList($contractModel->contract_code);
            if($authdata['success']) {
                $data['authappuselist'] = $authdata['data'];
            }else{
                $data['authappuselist'] = [];
            }
            $data['payover'] = $this->setFactUseData($data['payover'],$data['authappuselist']);
            $data['payover'] = $this->setEkpField($data['payover']);
        //}
        $this->saveApplicationShareAmount($data['application']);
        return $data;
    }

    private function setEkpField($payoverdata){
        $erpinterface = new ErpInterfaceService();
        foreach($payoverdata as &$item){
            if(!empty($item['stock_out_id'])){
                $authdata  = $erpinterface->GetDeliveryDetail($item['stock_out_id']);
                $products = $authdata['data']->YlInfo->Yl_Tenant[0]->Erp_Products;
                if (!empty($products)) {
                    foreach($products as $p){
                        if($item['application_id'] == $p->Product_Info_Id){
                            $item['DcYhzk'] = $p->DcYhzk;
                            $item['Qyzk'] = $p->Qyzk;
                            $item['DcSjzk'] = $p->DcSjzk;
                            $item['BenchmarkPrice'] = $p->BenchmarkPrice;
                        }
                    }
                }
            }
            if(empty($item['DcYhzk'])){
                $item['DcYhzk'] = '';
                $item['Qyzk'] = '';
                $item['DcSjzk'] = '';
                $item['BenchmarkPrice'] = '';
            }
        }
        return $payoverdata;
    }

    private function setFactUseData($payoverdata,$appuserdata){
        foreach($payoverdata as &$item){
            $factusernum = 0;
            foreach($appuserdata as $ii){
                if($item['application_id'] == $ii->product){
                    if(!empty($ii->auth_total)){
                        $factusernum += $ii->auth_total;
                    }
                    if(!empty($ii->details)){
                        foreach($ii->details as $m){
                            if($m->auth_id == $item['auth_id']){
                                $factusernum += 1;
                            }
                        }
                    }
                }
            }
            $item['factusernum'] = $factusernum;
        }
        return $payoverdata;
    }

    private function saveApplicationShareAmount($applist){
        foreach($applist as $app){
            $contractapp = ContractApplicationEntity::find()->where(['contract_application_id'=>$app['contract_application_id']])->one();
            $contractapp->rent_share_amount = $app['share_amount'];
            $contractapp->balance_share_amount = $app['share_balance_amount'];
            $contractapp->balance_should_amount = $app['balance_should_amount'];
            $contractapp->save();
        }
    }

    private function loadSpecialData($CstName,&$data){
        if($CstName == '碧桂园房地产'){
            $data['linkcontract']['customer_name'] = '碧桂园房地产';
            $data['linkcontract']['customer_full_name'] = '碧桂园房地产开发集团有限公司';
            $data['linkcontractrelation']['tenant_name'] = '碧桂园';
            $data['linkcontractrelation']['tenant_code'] = 'bgy';
            $data['linkcontractrelation']['kt_date'] = '2016-07-18';
            $data['linkcontract']['sign_people_id'] = '058ec358-e79c-47d0-8262-2fe0df40a334';
            $data['linkcontractother']['sign_people_name'] = '梁桂流';
            $data['linkcontractother']['area_name'] = '中山公司';
        }elseif($CstName == '南京华轩') {
            $data['linkcontract']['customer_name'] = '南京华轩(南京翠屏国际)';
            $data['linkcontract']['customer_full_name'] = '南京华轩房地产开发有限公司';
            $data['linkcontractrelation']['tenant_name'] = '南京华轩';
            $data['linkcontractrelation']['tenant_code'] = 'cpgj';
            $data['linkcontractrelation']['kt_date'] = '2017-03-08';
            $data['linkcontract']['sign_people_id'] = 'c1968ec0-3744-41f3-a19f-e8bf84773696';
            $data['linkcontractother']['sign_people_name'] = '张健';
            $data['linkcontractother']['area_name'] = '南京公司';
        }
    }

    private function getTenantInfoByCode($contactCode)
    {
        $tenant = TenantService::getContractTenantList($contactCode);
        if (!empty($tenant)) {
            return $tenant;
        }

        return [];
    }

    /**
     * 获取产品签约分摊金额
     * 取数公式=标准总额/标准总额合计*产品租金金额
     * @param type $data
     */
    private function getShareAmount($application_sum = 0, $deal_amount = 0,$sign_amount = 0,$area_id = '', $data = [])
    {
        $application_sum_act = 0;
        foreach ($data as $item) {
            $application_sum_act += $item['amount'];
        }

        if ($application_sum != $application_sum_act) {
            $application_sum = $application_sum_act;
        }

        foreach ($data as &$item) {
                $item["share_amount"] = $application_sum == 0 ? 0 : round($item['amount'] / $application_sum * $deal_amount, 2);
            //$item["share_sign_amount"] = $application_sum == 0 ? 0 : round($item['amount'] / $application_sum * $sign_amount, 2);

            $balancerate = ApplicationBalanceRateEntity::find()
                ->where(['application_id'=>$item['application_id']])
                ->andWhere('min_number<=' . $item['authorization_numeric'])
                ->andWhere('max_number>=' . $item['authorization_numeric'])
                ->one();
            if(empty($balancerate)){
                $item["share_balance_amount"] = 0;
            }else{
                //判断是否有针对区域做不同的比例设置
                $rate = $balancerate['rate'];
                if(!empty($area_id)){
                    $newrate = ApplicationBuRateEntity::find()->where(['balance_rate_id'=>$balancerate['balance_rate_id'],'BUGUID'=>$area_id])->one();
                    if(!empty($newrate)){
                        $rate = $newrate['rate'];
                    }
                }

                $item["share_balance_amount"] = (empty($item['amount'])?0:$item['amount']) *  $rate * $balancerate['discount'];
            }
            if(empty($item["balance_should_amount"]) || $item["balance_should_amount"] == 0) {
                $item["balance_should_amount"] = $item["share_balance_amount"];
            }
        }

        return $data;
    }

    /**
     * 提交复核
     * @param string $contractId 合同id
     * @return boolean
     */
    public function submitReview($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); //获取model

        if (empty($contractModel)) {//合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        if ($contractModel->contract_status != ContractManageEntity::APPROVE_STATUS_DRAFT) {//草稿状态，才能提交复核
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_SUBMIT_REVIEW_STATUS);
        }

        //判断是否有产品，没有产品不能提交复核 (非软件租用服务)
        if ($contractModel->business_type_id =='f85b3855-54ca-11e7-9f96-000c29310f8b' && $contractModel->littler_category_id != "62f81ca9-fcf4-11e4-bed8-00155d02c832" && !ContractApplicationRepository::isExistContractApplicationByContractId($contractId)) {
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_APPLICATION);
        }

        //供应商线下活动必须先填写返款金额
        if($contractModel->business_type_id =='f854fa59-54ca-11e7-9f96-000c29310f8b' && (empty($contractModel->back_amount) || $contractModel->back_amount == 0)){
            if(ContractPaymentRepository::getContractPaymentAmountByContractId($contractId)<=0) {
                return $this->setAndReturn('999', '请填写回款金额!', '请填写回款金额!');
            }
        }

//        //云客签约-直属区域/云客签约-联营区域 : 收入金额汇总 = 签约金额
//        if ($contractModel->contract_property_id == ContractPropertyEntity::MYYK_PROPERTY_DIRECTLY_UNDER_ID || $contractModel->contract_property_id == ContractPropertyEntity::MYYK_PROPERTY_JOINT_OPERATION_ID) {
//            $amount = $contractModel->sign_amount;
//        } else {
//            //明源签约-直属区域/明源签约-联营区域 /联营签约-明源结算/联营签约-云客结算:收入金额汇总=结算金额
//            $amount = $contractModel->balance_amount;
//        }
//        $amount = $contractModel->income_amount;

        //1、收入金额校验规则：收入金额汇总 和签约金额/结算金额必须一致
//        $contractRevenueSum = ContractRevenueRepository::getContractRevenueSumByContractId($contractId); //收入金额汇总
//        if ($contractRevenueSum != $amount) {
//            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_REVENUE_SUM);
//        }

        //2、应收金额校验规则：应收金额汇总 和结算金额必须一致
//        $contractReceivableSum = ContractReceivableRepository::getReceivableTotalAmountByContractId($contractId); //应收金额汇总
//        if ($contractReceivableSum != $contractModel->balance_amount) {
//            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_RECEIVABLE_SUM,"应收金额合计与结算金额不等,不允许提交复核!","应收金额合计与结算金额不等,不允许提交复核!");
//        }

        //3、签约业绩校验规则：签约业绩金额汇总 和签约金额/结算金额必须一致
//        $signAchievementAmount = SignAchievementRepository::getSignAchievementSumByContractId($contractId); //签约业绩金额
//        if ($signAchievementAmount != $amount) {
//            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_SIGN_ACHIEVEMENT_SUM);
//        }

        return ContractManageRepository::updateContractStatus($contractId, ContractManageEntity::APPROVE_STATUS_SUBMIT_HANDLE);
    }

    /**
     * 撤销复核
     * @param string $contractId 合同id
     * @return boolean
     */
    public function cancelReview($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); //获取model
        if (empty($contractModel)) {//合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        if ($contractModel->contract_status != ContractManageEntity::APPROVE_STATUS_SUBMIT_HANDLE) {//已审核合同不能撤销复核
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_CANCEL_REVIEW_STATUS);
        }

        return ContractManageRepository::updateContractStatus($contractId, ContractManageEntity::APPROVE_STATUS_DRAFT);
    }

    public function  cancelConfirmContract($contractId){
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); //获取model
        if (empty($contractModel)) {//合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }

        return ContractManageRepository::updateContractStatus($contractId, ContractManageEntity::APPROVE_STATUS_DRAFT);
    }

    /**
     * 合同复核
     * @param string $contractId 合同id
     * @return boolean
     */
    public function auditReview($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); //获取model
        if (empty($contractModel)) {//合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        if ($contractModel->contract_status != ContractManageEntity::APPROVE_STATUS_SUBMIT_HANDLE) {//提交复核状态，才能复核
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_AUDIT_REVIEW_STATUS);
        }
        $contractModel->review_date = ConfigEntity::getDbNowDate();
        $contractModel->save();

        //ContractManageRepository::updateContractInputDate($contractId); // 更新合同生效日期
        $result = ContractManageRepository::updateContractStatus($contractId, ContractManageEntity::APPROVE_STATUS_PASS);
        if ($this->getErrCode() == ErrorCode::SUCCESS) {
            //发生未关联发票提醒
            $existInvoice = InvoiceRepository::existInvoiceNotRelContract($contractModel->customer_full_name);
            if (!empty($existInvoice)) {
                $parms = [
                    'userName' => '薛维芝',
                    'contractId' => $contractModel->contract_code,
                    'custFullName' => $contractModel->customer_full_name,
                    'signAmount' => $contractModel->sign_amount
                ];
                try {
                    $this->sendMailHandler(['xuewz@mysoft.com.cn' => '薛维芝'], '【合同管理】已开票未关联合同', 'invoiceNoContract', $parms, []);
                }catch (Exception $ex){

                }
            }
        }

        return $result;
    }

    /**
     * 作废合同
     * @param string $contractId 合同id
     * @return boolean
     */
    public function cancelContract($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        if ($contractModel->contract_status == ContractManageEntity::APPROVE_STATUS_PASS) { // 已审核不能作废
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_CANCELLED_APPROVE_STATUS);
        }
        if ($contractModel->is_cancelled == ContractManageEntity::CONTRACT_IS_CANCELLED) { // 已作废,直接返回true
            return true;
        }

        //检查是否存在发票  存在发票不能作废
        if (InvoiceRepository::isExistContractInvoice($contractId)) {
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_EXIST_INVOICE);
        }

        //检查是否关联回款  存在回款不能作废
        if (ContractPaymentRepository::isExistContractPayment($contractId)) {
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_EXIST_PAYMENT);
        }

        return ContractManageRepository::updateContractCancelledStatusByContractId($contractId);
    }

    /**
     * 合同列表
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param int $status 合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
     * @param string $property 合同性质id
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param string $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $signPeopleId 签约人ID
     * @param string $invoiceType 0 发票 1收据 2发票和收据
     * @return array
     */
    public function getContractList($pageIndex, $pageSize, $sortBy, $sortAsc, $BusinessType,$status, $property, $keyword = '', $areaId = '', $invoiceType = null, $signPeopleId = '', $beginInputDate = null, $endInputDate = null,$isOver = '')
    {
        $pageParam = new PageParam($pageIndex, $pageSize, $sortBy, $sortAsc);
        #区域过滤
        if (empty($areaId)) {
            $areaId = self::filterBusinessUnit(\Yii::$app->user->identity);
        }

        $departmentId = self::filterDepartment(\Yii::$app->user->identity);

        $data = ContractManageRepository::getContractList($pageParam,$BusinessType, $status, $property, $keyword, $areaId, $invoiceType, $signPeopleId, $departmentId, $beginInputDate, $endInputDate,$isOver);
        if (empty($data)) {
            return $data;
        }

        $businessTypes = \Yii::$app->params['contract_types'];

        foreach ($data['items'] as $key => $val) {

            //获取租期
            $contract_repository = new MyscrmContractRepository();
            $contractInfo = $contract_repository->getContractByContractNum($val['contract_code']); //获取合同表信息

            if (empty($contractInfo)) {
                $data['items'][$key]['beginOn'] = '';
                $data['items'][$key]['endOn'] = '';
            } else {
                $data['items'][$key]['beginOn'] = $contractInfo->BeginOn;
                $data['items'][$key]['endOn'] = $contractInfo->EndOn;
            }

            $data['items'][$key]['property_name'] = ContractPropertyRepository::getPropertyNameByPropertyId($val['contract_property_id']); //获取性质名称
            $data['items'][$key]['category_name'] = ContractCategoryRepository::getCategoryNameByCategoryId($val ['category_id']); // 获取合同类别名称
            $data ['items'] [$key] ['company_name'] = ContractCompanyRepository::getContractCompanyNameByCompanyId($val['company_id']); // 获取公司名称
            $data ['items'] [$key] ['user_name'] = empty($val ['sign_people_id'])?$val ['sign_people_name']:ErpUserRepository::getUserNameByBuguid($val ['sign_people_id']); // 获取签约人名称
            $data ['items'] [$key] ['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($val ['area_id']); // 获取区域名称
            if($data['items'][$key]['business_type_id'] == 'f854fa59-54ca-11e7-9f96-000c29310f8b' ||
                $data['items'][$key]['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b' ||
                $data['items'][$key]['business_type_id'] == 'f851bc86-54ca-11e7-9f96-000c29310f8b'
            ) {
                $data ['items'] [$key] ['received_amount'] = ContractPaymentRepository::getContractPaymentAmountByContractId($data ['items'] [$key] ['contract_id']);
            }else{
                $data ['items'] [$key] ['received_amount'] = ContractReceivableRepository::getContractReceivedByContractId($data ['items'] [$key] ['contract_id']);
            }
            if(!empty($val['business_type_id'])){
                $businessTypeName = ContractBusinessTypeRepository::getBusinessTypeById($val['business_type_id'])['business_type_name'];
                $businessTypeCode = $businessTypes[$businessTypeName];
            }else{
                $businessTypeName = '';
                $businessTypeCode = '';
            }
            $data['items'][$key]['business_type_code'] = empty($businessTypeCode)?'':$businessTypeCode;//获取业务类型名称
            $data['items'][$key]['business_type_name'] = empty($businessTypeName)?'':$businessTypeName;
            if($data['items'][$key]['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b'){
                if(!empty($data['items'][$key]['link_contract_id'])) {
                    //供应商移动工程协同合同需要获取链接合同信息
                    $linkcon = ContractManageRepository::getContractManageModelByContractId($data['items'][$key]['link_contract_id']);
                    $data['items'][$key]['link_areaname'] = ErpBusinessUnitRepository::getBunameByBuguid($linkcon->area_id);;
                    $data ['items'] [$key] ['link_user_name'] = ErpUserRepository::getUserNameByBuguid($linkcon->sign_people_id);
                }else{
                    if($data['items'][$key]['customer_name'] == '碧桂园房地产'){
                        $data['items'][$key]['link_areaname'] = '中山公司';
                        $data ['items'] [$key] ['link_user_name'] = '梁桂流';
                    }elseif($data['items'][$key]['customer_name'] == '南京华轩'){
                        $data['items'][$key]['link_areaname'] = '南京公司';
                        $data ['items'] [$key] ['link_user_name'] = '张健';
                    }else {
                        $data['items'][$key]['link_areaname'] = '';
                        $data ['items'] [$key] ['link_user_name'] = '';
                    }
                }
            }
            //对于供应商名称为空的则取客户全称
            if (empty($data['items'][$key]['supplier_name'])) {
                $data['items'][$key]['supplier_name'] = $data['items'][$key]['customer_full_name'];
            }
        }

        return $data;
    }

    /**
     * 取云链直销合同的签约业绩合同明细数据
     */
    public static function getDirectContract($beginTime = '',$endTime = '')
    {
        $data = ContractManageRepository::getDirectContract($beginTime,$endTime);
        if (empty($data)) {
            return [];
        }
        foreach($data as $key => $val){
            $sign_people_id = '';
            if($data[$key]['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b'){
                if(!empty($data[$key]['link_contract_id'])){
                    $linkcon = ContractManageRepository::getContractManageModelByContractId($data[$key]['link_contract_id']);
                    $data[$key]['sign_people_name'] = ErpUserRepository::getUserNameByBuguid($linkcon->sign_people_id);
                    $data[$key]['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($linkcon->area_id);
                    $sign_people_id = $linkcon->sign_people_id;
                }else{
                    if($data[$key]['customer_name'] == '碧桂园房地产'){
                        $data[$key]['area_name'] = '中山公司';
                        $data[$key]['sign_people_name'] = '梁桂流';
                        $sign_people_id = '058ec358-e79c-47d0-8262-2fe0df40a334';
                    }elseif($data[$key]['customer_name'] == '南京华轩'){
                        $data[$key]['area_name'] = '南京公司';
                        $data[$key]['sign_people_name'] = '张健';
                        $sign_people_id = 'c1968ec0-3744-41f3-a19f-e8bf84773696';
                    }else {
                        $data[$key]['area_name'] = '';
                        $data[$key]['sign_people_name'] = '';
                    }
                }
            }
            if($sign_people_id){
                $erpInterfaceService = Yii::createObject(ErpInterfaceService::className());
                $signUserData = $erpInterfaceService->getUserInfoById($sign_people_id);
                $data[$key]['department_guid'] = $signUserData['DepartmentGUID'];
                $data[$key]['department_name'] = $signUserData['DepartmentName'];
            } else {
                $data[$key]['department_guid'] = '';
                $data[$key]['department_name'] = '';
            }
        }
        return $data;
    }

    /**
     * 取云链直销合同的回款业绩明细数据
     */
    public static function getDirectContractPayment($beginTime = '',$endTime = ''){
        $data = ContractManageRepository::getDirectContractPayment($beginTime,$endTime);
        if (empty($data)) {
            return [];
        }
        foreach($data as $key => $val){
            $sign_people_id = '';
            if($data[$key]['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b'){
                if(!empty($data[$key]['link_contract_id'])){
                    $linkcon = ContractManageRepository::getContractManageModelByContractId($data[$key]['link_contract_id']);
                    $data[$key]['sign_people_name'] = ErpUserRepository::getUserNameByBuguid($linkcon->sign_people_id);
                    $data[$key]['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($linkcon->area_id);
                    $sign_people_id = $linkcon->sign_people_id;
                }else{
                    if($data[$key]['customer_name'] == '碧桂园房地产'){
                        $data[$key]['area_name'] = '中山公司';
                        $data[$key]['sign_people_name'] = '梁桂流';
                        $sign_people_id = '058ec358-e79c-47d0-8262-2fe0df40a334';
                    }elseif($data[$key]['customer_name'] == '南京华轩'){
                        $data[$key]['area_name'] = '南京公司';
                        $data[$key]['sign_people_name'] = '张健';
                        $sign_people_id = 'c1968ec0-3744-41f3-a19f-e8bf84773696';
                    }else {
                        $data[$key]['area_name'] = '';
                        $data[$key]['sign_people_name'] = '';
                    }
                }
            }
            if ($sign_people_id) {
                $erpInterfaceService = Yii::createObject(ErpInterfaceService::className());
                $signUserData = $erpInterfaceService->getUserInfoById($sign_people_id);
                $data[$key]['department_guid'] = $signUserData['DepartmentGUID'];
                $data[$key]['department_name'] = $signUserData['DepartmentName'];
            } else {
                $data[$key]['department_guid'] = '';
                $data[$key]['department_name'] = '';
            }
        }
        return $data;
    }

    /**
     * 获取釆宝类合同列表数据
     * @param $pageIndex
     * @param $pageSize
     * @param null $beginInputDate
     * @param null $endInputDate
     */
    public function getContractCaibaoList($pageIndex, $pageSize, $beginInputDate = null, $endInputDate = null){
        $pageParam = new PageParam($pageIndex, $pageSize,'input_date',false);
        $data = ContractManageRepository::getContractCaibaoList($pageParam, $beginInputDate, $endInputDate);
        if (empty($data)) {
            return $data;
        }

        $businessTypes = \Yii::$app->params['contract_types'];

        foreach ($data['items'] as $key => $val) {
            if(!empty($val['business_type_id'])){
                $businessTypeName = ContractBusinessTypeRepository::getBusinessTypeById($val['business_type_id'])['business_type_name'];
                $businessTypeCode = $businessTypes[$businessTypeName];
            }else{
                $businessTypeName = '';
                $businessTypeCode = '';
            }
            $data['items'][$key]['business_type_code'] = empty($businessTypeCode)?'':$businessTypeCode;//获取业务类型名称
            $data['items'][$key]['business_type_name'] = empty($businessTypeName)?'':$businessTypeName;
        }
        return $data;
    }

    /**
     * 导出未结算合同列表
     * @param boolean $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $beginDate 结算开始时间
     * @param string $endDate 结算结束时间
     * @return array
     */
    public function exportBalanceContractListExcel($property, $keyword, $areaId, $beginDate, $endDate,$status,$backstatus)
    {
        #区域过滤
        if (empty($areaId)) {
            $areaId = self::filterBusinessUnit(\Yii::$app->user->identity);
        }

        $data = ContractManageRepository::getExportBalanceContractListExecl($property, $keyword, $areaId, $beginDate, $endDate,$status,$backstatus);

        $objPHPExcel = new \PHPExcel();
        //设置当前的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //设置sheet的name
        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        //设置单元格的值
        $objPHPExcel->getActiveSheet()->setCellValue('A1', '合同GUID');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '客户名称');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '客户简称');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '合同编号');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '合同性质');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '合同类别');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '合同签署公司');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '合同所属区域');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '签约人');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '签约日期');
        $objPHPExcel->getActiveSheet()->setCellValue('K1', '签约金额');
        $objPHPExcel->getActiveSheet()->setCellValue('L1', '已回款金额');

        $objPHPExcel->getActiveSheet()->setCellValue('M1', '租用金额');
        $objPHPExcel->getActiveSheet()->setCellValue('N1', '交付金额');
        $objPHPExcel->getActiveSheet()->setCellValue('O1', '结算金额');
        $objPHPExcel->getActiveSheet()->setCellValue('P1', '结算日期');
        $objPHPExcel->getActiveSheet()->setCellValue('Q1', '结算状态');
        $objPHPExcel->getActiveSheet()->setCellValue('R1', '返款金额');
        $objPHPExcel->getActiveSheet()->setCellValue('S1', '返款日期');
        $objPHPExcel->getActiveSheet()->setCellValue('T1', '返款状态');
        $objPHPExcel->getActiveSheet()->setCellValue('U1', '是否收票');
        $objPHPExcel->getActiveSheet()->setCellValue('V1', '发票代码');

        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['contract_id']); // 合同GUID
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['customer_full_name']); //客户名称
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, ContractPropertyRepository::getPropertyNameByPropertyId($val['contract_property_id'])); //合同性质
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, ContractCategoryRepository::getCategoryNameByCategoryId($val ['category_id'])); //合同类别
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, ContractCompanyRepository::getContractCompanyNameByCompanyId($val['company_id'])); //合同签署公司
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, ErpBusinessUnitRepository::getBunameByBuguid($val ['area_id'])); //合同所属区域
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, ErpUserRepository::getUserNameByBuguid($val ['sign_people_id'])); //签约人
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['sign_date']); //签约日期
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['sign_amount']); //签约金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $this->getPayMentAmount($val['contract_id'])); //已回款金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['rent_amount']); //租用金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['delivery_amount']); //交付金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['balance_amount']); //结算金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['balance_date']); //结算日期
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['balance_status']==0?'未结算':($val['balance_status']==1?'已结算':'部分结算')); //结算状态
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['back_amount']); //返款金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['back_date']); //返款日期
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, empty($val['back_status']) ? '未返款' : '已返款'); //返款状态
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['back_receive_status']==1 ? '已收票' : '未收票'); //是否收票
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['back_invoice_code']); //返款发票代码

                $j++;
            }
        }

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setVisible(false); //把合同guid 设置为隐藏列
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="合同结算清单' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    //获取合同的回款金额
    private function getPayMentAmount($contractId){
        // 应收款项信息
        $paymentAmount = 0;
        $receivables = $this->getReceivableInfoByContractId($contractId);
        if (isset($receivables) && count($receivables) > 0) {
            foreach ($receivables as $k => $v) {
                $paymentAmount += floatval($v['received_amount']);
            }
        }
        return $paymentAmount;
    }

    /**
     * 导入结算合同列表
     * @return boolean
     */
    public function importBalanceContractListExecl()
    {
        if (empty($_FILES ['file'])) {
            return $this->setAndReturn(-1, '', '上传文件不能为空');
        }
        $filename = explode('.', $_FILES ['file'] ['name']);
        if ($filename [1] != 'xls' && $filename [1] != 'xlsx') {
            return $this->setAndReturn(-1, '', '请上传EXCEL文件');
        }

        $arr = ExcelManage::importDataByFilePath($_FILES['file']['tmp_name'], 0);

        if (!empty($arr) && count($arr) >= 3) {//导入文件行数不能少于3.因为第3行开始是数据
            $db = ConfigEntity::getDb();
            $trans = $db->beginTransaction(); //开启事务
            foreach ($arr as $key => $val) {
                if ($key > 1) {//前两行数据，为无关数据
                    $contractId = $val[0];
                    if (empty($contractId)) {
                        continue;
                    }
                    //todo 15 结算日期 16 结算状态 18 返款日期  19 返款状态
                    if (isset($val[15]) || isset($val[19])) {
                        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
                        if (empty($contractModel)) { // 合同不存在
                            continue;
                        }

                        if ($val[16] == '已结算') {
                            $contractModel->balance_status = ContractManageEntity::CONTRACT_BALANCE_STATUS;
                            //$back_date = strtotime(PHPExcel_Shared_Date::ExcelToPHP($val[15]));
                            if(empty($val[15])) {
                                $balance_date = ConfigEntity::getDbNowDate();
                            }else{
                                if(strpos($val[15], '.') === false) {
                                    //2018/5/28格式导入进来为5位数字,为它初始化多1秒
                                    $back_date = strlen($val[15]) == 5 ? PHPExcel_Shared_Date::ExcelToPHP(($val[15].'.00001157408')) : strtotime($val[15]);
                                }else{
                                    $back_date = PHPExcel_Shared_Date::ExcelToPHP($val[15]);
                                }
                                $balance_date = gmdate('Y-m-d', $back_date);
                            }
                            $contractModel->balance_date = $balance_date;
                            $contractModel->balance_amount = empty($val[14])?0:$val[14];
                        } elseif($val[16] == '部分结算') {
                            $contractModel->balance_status = ContractManageEntity::CONTRACT_PART_BALANCE_STATUS;
                            //$back_date = strtotime(PHPExcel_Shared_Date::ExcelToPHP($val[15]));
                            if(empty($val[15])) {
                                $balance_date = ConfigEntity::getDbNowDate();
                            }else{
                                if(strpos($val[15], '.') === false) {
                                    //2018/5/28格式导入进来为5位数字,为它初始化多1秒
                                    $back_date = strlen($val[15]) == 5 ? PHPExcel_Shared_Date::ExcelToPHP(($val[15].'.00001157408')) : strtotime($val[15]);
                                }else{
                                    $back_date = PHPExcel_Shared_Date::ExcelToPHP($val[15]);
                                }
                                $balance_date = gmdate('Y-m-d', $back_date);
                            }
                            $contractModel->balance_date = $balance_date;
                            $contractModel->balance_amount = $val[14];
                        }else{
                            $contractModel->balance_status = ContractManageEntity::CONTRACT_NOT_BALANCE_STATUS;
                            $contractModel->balance_date = null;
                        }

                        if ($val[19] == '已返款') {
                            $contractModel->back_status = ContractManageEntity::CONTRACT_BACK_STATUS;
                            //$back_date = strtotime(PHPExcel_Shared_Date::ExcelToPHP($val[18]));
                            if(empty($val[18])) {
                                $balance_date = ConfigEntity::getDbNowDate();
                            }else{
                                if(strpos($val[18], '.') === false) {
                                    //2018/5/28格式导入进来为5位数字,为它初始化多1秒
                                    $back_date = strlen($val[18]) == 5 ? PHPExcel_Shared_Date::ExcelToPHP(($val[18].'.00001157408')) : strtotime($val[18]);
                                }else{
                                    $back_date = PHPExcel_Shared_Date::ExcelToPHP($val[18]);
                                }
                                $balance_date = gmdate('Y-m-d', $back_date);
                            }
                            $contractModel->back_date = $balance_date;
                        } else {
                            $contractModel->back_status = ContractManageEntity::CONTRACT_NOT_BACK_STATUS;
                            $contractModel->back_date = null;
                        }
                        $contractModel->back_amount = empty($val[17])?0:$val[17];
                        $contractModel->back_receive_status = $val[20]=='已收票'?1:0;
                        $contractModel->back_invoice_code = $val[21];

                        if ($contractModel->save() == false) {
                            $trans->rollBack();

                            return $this->setAndReturn(-1, '', '更新失败,合同编号：' . $val[3]);
                        }
                    } else {
                        continue;
                    }
                }
            }
            $trans->commit();
        }

        return ['path' => ''];
    }

    /**
     * 获取结算合同列表
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param int $status 结算状态 0：未结算 1：已结算
     * @param string $property 合同性质id
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $beginDate 结算开始时间
     * @param string $endDate 结算结束时间
     */
    public function getBalanceContractList($pageIndex, $pageSize, $sortBy, $sortAsc ,$BusinessType,$backstatus, $status, $property, $keyword, $areaId, $beginDate, $endDate)
    {
        $pageParam = new PageParam($pageIndex, $pageSize, $sortBy, $sortAsc);
        #区域过滤
        if (empty($areaId)) {
            $areaId = self::filterBusinessUnit(\Yii::$app->user->identity);
        }
        $data = ContractManageRepository::getBalanceContractList($pageParam,$BusinessType, $backstatus, $status, $property, $keyword, $areaId, $beginDate, $endDate);
        if (empty($data)) {
            return $data;
        }
        $businessTypes = \Yii::$app->params['contract_types'];

        foreach ($data['items'] as $key => $val) {
            $data['items'][$key]['property_name'] = ContractPropertyRepository::getPropertyNameByPropertyId($val['contract_property_id']); //获取性质名称
            $data['items'][$key]['category_name'] = ContractCategoryRepository::getCategoryNameByCategoryId($val['category_id']); //获取合同类别名称
            $data['items'][$key]['company_name'] = ContractCompanyRepository::getContractCompanyNameByCompanyId($val['company_id']); // 获取公司名称
            $data['items'][$key]['user_name'] = ErpUserRepository::getUserNameByBuguid($val['sign_people_id']); //获取签约人名称
            $data['items'][$key]['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($val['area_id']); //获取区域名称
            $data['items'][$key]['payment_amount'] = $this->getPayMentAmount($val['contract_id']);

            if(!empty($val['business_type_id'])){
                $businessTypeName = ContractBusinessTypeRepository::getBusinessTypeById($val['business_type_id'])['business_type_name'];
                $businessTypeCode = $businessTypes[$businessTypeName];
            }else{
                $businessTypeCode = '';
            }
            $data['items'][$key]['business_type_code'] = empty($businessTypeCode)?'':$businessTypeCode;//获取业务类型名称
        }


        $data['items'] = $this->getTenantInfo($data['items']);

        return $data;
    }

//    private static $all_area_user_list = [
//        '8b90a9a1-49eb-4cc1-8e1a-a18172cc477a',//蒋琴
//        '77450379-de98-4304-beb2-8657619f37b6',//郭昊
//        '0ec237ff-416f-49bf-9e2d-0ebf75cbf25e',//张宇
//        'af5ee9d5-b30e-4735-a8e8-4c66ec6289c3',//朱姿
//        '314ce17c-8be2-e411-9b71-848f69dfab18',//陈文
//        '83370496-60c1-4b5c-baae-48aa0f8e19d9',//薛维芝
//        '1f34b45b-daf2-41f7-a7e5-298cc83a847d', //王瑾
//        '8b90a9a1-49eb-4cc1-8e1a-a18172cc477a',//蒋琴
//        '77450379-de98-4304-beb2-8657619f37b6',//郭昊
//        'a3c8f32d-374b-4772-95e9-0f3a84f2f1a1',//付小玲
//        '4bd0d121-bfbd-e211-b240-848f69dfab18',//唐亮
//        '3bc0b24b-7014-424c-9761-b6a9aae92c40',//肖志淼
//        '31f960f4-8a9f-455f-b9a0-9758676c9fc9',//刘丽丽
//        '359fa58b-fc41-e411-aad8-848f69dfab18', //孟兵
//        'a12726c9-41fc-e311-85be-848f69dfab18', //徐大成
//    ];

    /**
     * 判断用户是否过滤所属区域数据
     * @param $user
     * @return false:不需要过滤，BUGUID：公司ID
     */
    public static function filterBusinessUnit($user)
    {
        $userEntity = ErpInterfaceService::getUserByCode($user->usercode);
        #显示全部区域数据
        if ($userEntity->ViewAllArea) {
            return false;
        }
        return ErpInterfaceService::getSubBuGuidsByBuGuid($userEntity->BUGUID);
    }

    public static function filterDepartment($user)
    {
        $userEntity = ErpInterfaceService::getUserByCode($user->usercode);
        #显示本部门
        if ($userEntity->OnlyViewMyselfDepartment) {
            return $userEntity->DepartmentGUID;
        }

        return '';
    }

    /**
     * 获取合同城市区域列表
     * @return array
     */
    public function getContractAreaList()
    {
        $buGuid = self::filterBusinessUnit(\Yii::$app->user->identity);
        $areaIdList = ContractManageRepository::getContractAreaIdList($buGuid);
        if (empty($areaIdList)) {
            return [];
        }
        $data = [];
        foreach ($areaIdList as $key => $val) {
            $areaName = ErpBusinessUnitRepository::getBunameByBuguid($val->area_id); //获取区域公司名称
            if (!empty($areaName)) {
                $data1['areaId'] = $val->area_id;
                $data1['areaName'] = $areaName;
                array_push($data, $data1);
            }
        }

        return $data;
    }

    /**
     * 获取合同签约区域列表
     */
    public function getAreaInfo($keyword, $limit){
        $areaList = ErpBusinessUnitRepository::getAreaList($keyword, $limit);
        return $areaList;
    }

    public function updateRevenueInfo($revenueId, $noconfirmbadamount, $haveconfirmbadamount,$kingdieverifbadamount){
        $res = false;
        $revenue = ContractRevenueEntity::find()->where(['revenue_id'=>$revenueId])->one();
        $before = $revenue?$revenue->getAttributes():false;
        if(!empty($revenue)){
            $revenue->no_confirm_bad_amount = empty($noconfirmbadamount)?0:$noconfirmbadamount;
            $revenue->have_confirm_bad_amount = empty($haveconfirmbadamount)?0:$haveconfirmbadamount;
            $revenue->kingdie_verif_bad_amount = empty($kingdieverifbadamount)?0:$kingdieverifbadamount;
            $revenue->modified_on = ConfigEntity::getDbNowDate();
            $now = $revenue?$revenue->getAttributes():false;
            $res = $revenue->save();

            IncomeItemLogRepository::add($before,$now,$res,IncomeItemLogRepository::OPERATE_EDIT);
        }
        return $res;
    }

    public function updateRevenueCarryoverInfo($carryoverId,$revenueId, $changeamount, $changebeforethisperiodconfirmtotalamount,$thisperiodconfirmtotalamount,$thisperiodconfirmamount){
        $res = false;
        $carryover = ContractRevenueCarryoverEntity::find()->where(['carryover_id'=>$carryoverId])->one();
        if(!empty($carryover)) {
            $transaction = ContractRevenueEntity::getDb()->beginTransaction();
            try {
                $carryover->change_amount = empty($changeamount) ? 0 : $changeamount;
                $carryover->change_before_this_period_confirm_total_amount = empty($changebeforethisperiodconfirmtotalamount) ? 0 : $changebeforethisperiodconfirmtotalamount;
                $carryover->this_period_confirm_total_amount = empty($thisperiodconfirmtotalamount)?0:$thisperiodconfirmtotalamount;
                $carryover->this_period_confirm_amount = empty($thisperiodconfirmamount) ? 0 : $thisperiodconfirmamount;
                $carryover->modified_on = ConfigEntity::getDbNowDate();
                $res = $carryover->save();
                //保存后更新应收信息的状态
                $this->refreshRevenueData($revenueId,$carryoverId);
                $transaction->commit();
                $res = true;
            }catch (Exception $ex){
                $transaction->rollBack();
            }
        }
        return $res;
    }

    /**
     * 刷新应收款数据
     * @param $revenueid
     */
    private function refreshRevenueData($revenueid,$carryoverId){
        $sql = "UPDATE myscrm_contract_revenue r
                inner join myscrm_contract_revenue_carryover c on r.revenue_id=c.revenue_id
                SET r.total_confirm_amount=c.this_period_confirm_total_amount,
                r.wait_confirm_amount=r.amount-r.total_confirm_amount,
                r.close_status=IF(r.wait_confirm_amount=0,1,0),r.modified_on = NOW()
                WHERE r.revenue_id=:revenue_id AND c.carryover_id=:carryover_id";
        return ContractRevenueEntity::getDb()->createCommand($sql,[':revenue_id'=>$revenueid,':carryover_id'=>$carryoverId])->execute();
    }

    /**
     * 获取合同收入信息
     * @param string $contractId 合同id
     * @return array
     */
    public function getContractRevenue($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        //获取租期
        $contract_repository = new MyscrmContractRepository();
        $contractInfo = $contract_repository->getContractByContractNum($contractModel->contract_code); //获取合同表信息

        $data['account_company_id'] = $contractModel->account_company_id;
        $data['revenueList'] = ContractRevenueRepository::getContractRevenueListByContractId($contractId);
        if($contractModel->business_type_id == '9a96f3dc-54ca-11e7-9f96-000c29310f8b') {
            foreach ($data['revenueList'] as $key => $revenue){
                $data['revenueList'][$key]['type_name'] = '移动工程协同';
            }
        }
        $data['carryoverList'] = ContractRevenueCarryoverRepository::getCarryoverListByContractId($contractId);
        $data['contractInfo'] = $contractInfo;

        //获取租期信息
        if (empty($contractInfo)) {
            $data['beginOn'] = '';
            $data['endOn'] = '';
        } else {
            $data['beginOn'] = $contractInfo->BeginOn;
            $data['endOn'] = $contractInfo->EndOn;
        }

        return $data;
    }

    public function getContractRevenueById($oid){
        $data = ContractRevenueRepository::getContractRevenueById($oid);
        return $data;
    }

    public function getCarryoverById($oid){
        $data = ContractRevenueCarryoverRepository::getCarryoverById($oid);
        return $data;
    }

    /**
     * 处理保存收入信息数据
     * @param string $contractId 合同id
     * @param string $accountCompanyId 帐套公司id
     * @param array $revenueArr
     * @return boolean
     */
    public function submitRevenue($contractId, $accountCompanyId, $revenueArr)
    {
        if (empty($accountCompanyId)) {//帐套公司不能为空
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_COMPANY);
        }
        if (empty($revenueArr)) {//收入信息不能为空
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_REVENUE);
        }

        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        if ($contractModel->contract_status == ContractManageEntity::APPROVE_STATUS_PASS) { // 已审核不能修改
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_APPROVE_STATUS);
        }
        $contractModel->account_company_id = $accountCompanyId;
        $contractModel->save(); //更新。暂不作成功与否处理

        foreach ($revenueArr as $val) {
            if (!isset($val['__type'])) {
                $val['__type'] = 'update';
            }

            switch ($val['__type']) {
                case 'add':
                case '':
                    $contractRevenueModel = new ContractRevenueModel(); //增加场景
                    $contractRevenueModel->setScenario('add');
                    $contractRevenueModel->load($val, '');
                    $manageEntity = ContractManageRepository::getContractManageModelByContractId($contractId);
                    $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
                    $num = $manageEntity->inc;
                    $num < 10 && $num = "0" . $num;
                    $contractRevenueModel->income_code = $contractModel->contract_code . "-SR-" . $num; // 生成收入项编码
                    if ($contractRevenueModel->validate()) {
                        ContractRevenueRepository::addContractRevenueRecord($contractRevenueModel, $contractId); //新增收入
                    }
                    $manageEntity->save();
                    break;
                case 'update':
                    $contractRevenueModel = new ContractRevenueModel(); //更新场景
                    $contractRevenueModel->setScenario('update');
                    $contractRevenueModel->load($val, '');
                    if ($contractRevenueModel->validate()) {
                        ContractRevenueRepository::updateContractRevenueRecord($contractRevenueModel); //更改收入
                    }
                    break;
                case 'delete':
                    ContractRevenueRepository::deleteContractRevenueByRevenueId($val['revenue_id']); //删除收入
                    break;
            }
        }

        return true;
    }

    /**
     * 保存结算与返款信息
     * @param array $data 提交合同返款数据
     * @return boolean
     */
    public function updateContractAccount($contractBaseInfo,$isSave = false)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractBaseInfo['contract_id']); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }

        //saas产品保存是需要校验已结算金额等于应收款金额合计
        if($contractModel->business_type_id == 'f85b3855-54ca-11e7-9f96-000c29310f8b' && $isSave) {
            $contractReceivableSum = ContractReceivableRepository::getReceivableTotalAmountByContractId($contractBaseInfo['contract_id']); //应收金额汇总
            if ($contractReceivableSum != $contractModel->balance_amount) {
                return $this->setAndReturn(ErrorCode::ERR_CONTRACT_RECEIVABLE_SUM,"应收金额合计与结算金额不等,不允许保存!","应收金额合计与结算金额不等,不允许保存!");
            }
        }

        $balanceShouldAmount = $contractBaseInfo['balance_should_amount'];
        $balanceAmount = $contractBaseInfo['balance_amount'];
        $balanceStatus = 0;
        if(empty($balanceShouldAmount)){
            $balanceShouldAmount = 0;
        };
        if(empty($balanceAmount)){
            $balanceAmount = 0;
        };
        if($balanceAmount<=0){
            $balanceStatus = 0;     //未结算
        }else{
            if($balanceAmount >= $balanceShouldAmount){
                $balanceStatus = 1; //已结算
            }else{
                $balanceStatus = 2; //部分结算
            }
        };

        $contractModel->balance_should_amount = $contractBaseInfo['balance_should_amount']; //结算类型 0：标准结算 1：特价结算 2：特批其他
        $contractModel->balance_amount = $contractBaseInfo['balance_amount']; //结算金额
        $contractModel->balance_status = $balanceStatus;
        $contractModel->back_amount = empty($contractBaseInfo['back_amount'])?0:$contractBaseInfo['back_amount']; //返款金额
        $contractModel->back_date = empty($contractBaseInfo['back_date'])?null:$contractBaseInfo['back_date']; //返款时间
        if(!empty($contractModel->back_date)){
            $contractModel->back_status = 1;    //已返款
        }else{
            $contractModel->back_status = 0;    //未返款
        }
        $contractModel->back_receive_status = empty($contractBaseInfo['back_receive_status'])?0:$contractBaseInfo['back_receive_status']; //是否收票
        $contractModel->back_invoice_code = empty($contractBaseInfo['back_invoice_code'])?'':$contractBaseInfo['back_invoice_code']; //发票编码
        $contractModel->balance_remark = $contractBaseInfo['balance_remark']; //结算备注
        $contractModel->modified_on = ConfigEntity::getDbNowDate();
        $contractModel->save();

        //根据结算数据生成出库信息
        $this->generalShipment($contractModel->contract_id);

        //根据结算数据生成收入信息,saas类合同使用
        if($contractModel->business_type_id == 'f85b3855-54ca-11e7-9f96-000c29310f8b') {
            $this->generalReceivable($contractModel->contract_id,$contractModel->erp_contract_id,$contractModel->erp_contract_code,$contractModel->balance_amount);
            $this->generalIncomes($contractModel->contract_id,$contractModel->erp_contract_id,$contractModel->erp_contract_code,$contractModel->balance_amount);
        }
        $result = true;
        //调用接口,返回产品的出库信息给ekp
        if(!empty($contractModel->erp_contract_id) && YII_ENV_PROD) {
            $data = ContractManageRepository::getPushEkpReceivableData($contractBaseInfo['contract_id']);
            $erpInterFace = new ErpInterfaceService();
            $result = $erpInterFace->updateProductInfos($data);
        }
        return $result;
    }

    //根据结算数据生成出库信息
    public static function generalShipment($contractid){
        ContractShipmentEntity::deleteAll(['contract_id'=>$contractid]);

        $payovers = ContractPayoverEntity::find()
            ->where(['contract_id'=>$contractid])
            ->all();
        foreach($payovers as $item){
            if($item->balance_amount == 0 && $item->shipment_old_amount == 0){
                continue;
            }

            $kttime = substr($item->authorize_time,0,10);
            $shipment = ContractShipmentEntity::find()
                ->where(['contract_id'=>$contractid])
                ->andFilterWhere(['like','shipment_time',$kttime])
                ->one();
            if($shipment){
                //如果存在同日期的出库记录则只更新金额
                $shipment->amount = $shipment->amount + $item->balance_amount;

                $shipment->shipment_numberic = $shipment->shipment_numberic + $item->authorization_numeric;

                $shipment->modified_on = ConfigEntity::getDbNowDate();
                if(!$shipment->save()){
                    return false;
                }
                //交付表记录出库ID
                $item->shipment_id = $shipment->shipment_id;
            }else{
                //如果不存在同日期的出库记录则新增出库记录
                $newshipment = new ContractShipmentEntity();
                $shipmentid = StringHelper::uuid();
                $newshipment->shipment_id = $shipmentid;
                $newshipment->contract_id = $contractid;
                $newshipment->shipment_time = $item->authorize_time;
                $newshipment->amount = $item->balance_amount;
                $newshipment->shipment_numberic = $item->authorization_numeric;
                $newshipment->created_on = ConfigEntity::getDbNowDate();
                if(!$newshipment->save()){
                    return false;
                }
                //交付表记录出库ID
                $item->shipment_id = $shipmentid;
            }
            $item->shipment_old_amount = $item->balance_amount;
            $item->shipment_old_numberic = $item->authorization_numeric;
            $item->shipment_status = 1;
            if(!$item->save()){
                return false;
            }
        }
        return true;
    }

    //根据结算数据生成应收款信息
    private function generalReceivable($contractid){
        $payovers = ContractPayoverEntity::find()
            ->where(['contract_id'=>$contractid])
            ->all();
        $data = array();
        $receivable_item_id = '';
        $money_category_item_id = '';
        $payee_id = '39922166-833f-e711-80ed-8be4e954f9ce';//乔慧慧
        $erp_user = ErpUserRepository::getUserById($payee_id);
        $department_id = $erp_user->DepartmentGUID;
        $remark = '保存结算信息时自动生成';
        $pay_condition = '款到开通账号';
        foreach($payovers as $item){
            $app_info = ApplicationInfoRepository::getApplicationInfoById($item->application_id);
            $revenue_type = $app_info->IncomeTypeID;
            if($revenue_type == '8fd17068-5eb4-4588-816d-8376bba2caf7'){//云链租用服务
                $receivable_item_id = '9bbb275d-5b11-11e7-9f96-000c29310f8b';
                $money_category_item_id = 'd7a390f4-5d67-11e7-baca-7cd30abeb912';
            }
            elseif($revenue_type == 'a8d08aa9-baad-4279-bbe1-1d05852b9e38'){//云链增值服务
                $receivable_item_id = '882-fd02-11e4-bed8-00155d02c832';
                $money_category_item_id = 'b83d5b29-c3d1-11e5-8304-1051721c3a82';
            }
            $receivable_date = date('Y-m-d',strtotime($item->authorize_time));
            if(empty($receivable_date) || $receivable_item_id == '' || $money_category_item_id == '' || $receivable_date == ''){
                continue;
            }
            $key = md5($revenue_type.$receivable_date);
            if(isset($data[$key])){
                $data[$key]['balance_amount'] += $item->balance_amount;

            }else{
                $data[$key]['balance_amount'] = $item->balance_amount;
            }
            $data[$key]['revenue_type'] = $revenue_type;
            $data[$key]['receivable_date'] = $receivable_date;
            $data[$key]['receivable_item_id'] = $receivable_item_id;
            $data[$key]['money_category_item_id'] = $money_category_item_id;
        }

        foreach ($data as $sum){
            $load = [];
            $received = ContractReceivableRepository::isGeneralReceived($sum['revenue_type'],$sum['receivable_item_id'],$sum['money_category_item_id'],$sum['receivable_date'],$contractid);
            if($received){
                $invoice = InvoiceReceivableRepository::getInvoiceReceivablesByReceivableId($received->receivable_id);//是否绑定发票
                if($received->payee_id == $payee_id && $received->is_bad_debt == 0 ){
                    if($item['balance_amount'] > 0 && empty($invoice)){
                        $received->receivable_amount = $sum['balance_amount'];
                        $data['contract_property'] = 0;
                        $received->save();
                    }
                }
            }else{
                if($sum['balance_amount'] > 0){
                    $load['revenue_type'] = $sum['revenue_type'];
                    $load['contract_id'] = $contractid;
                    $load['receivable_item_id'] = $sum['receivable_item_id'];
                    $load['money_category_item_id'] = $sum['money_category_item_id'];
                    $load['receivable_date'] = $sum['receivable_date'];
                    $load['payee_id'] = $payee_id;
                    $load['department_id'] = $department_id;
                    $load['remark'] = $remark;
                    $load['created_on'] = date('Y-m-d H:i:s');
                    $load['created_by'] = $erp_user->UserName;
                    $load['modified_on'] = date('Y-m-d H:i:s');
                    $load['modified_by'] = $erp_user->UserName;
                    $load['payment_condition'] = $pay_condition;
                    $load['receivable_amount'] = $sum['balance_amount'];
                    $load['contract_property'] = 0;
                }
                if($load){
                    $contractReceivableModel = new ContractReceivableModel(['scenario' => 'savecontractreceivable']);
                    $contractReceivableModel->load($load, '');
                    $this->_contractReceivableService->saveContractReceivable($contractReceivableModel);
                }
            }
        }
    }

    //根据结算数据生成收入信息
    private function generalIncomes($contractid,$erpcontractid,$erpcontractcode,$balanceamount){
        $payovers = ContractPayoverEntity::find()
            ->where(['contract_id'=>$contractid])
            ->all();
        foreach($payovers as $item){
            //判断对应的结算信息是否已有对应的结算信息,已结算的不再做任何处理
            $isHaveCarryover = ContractRevenueRepository::isHaveCarryover($contractid,$item->contract_payover_id);
            if($isHaveCarryover){
                continue;
            }
            $newincome = ContractRevenueEntity::find()->where(['contract_id'=>$contractid,'contract_payover_id'=>$item->contract_payover_id])->one();
            $before = $newincome?$newincome->getAttributes():false;
            $manageEntity = ContractManageRepository::getContractManageModelByContractId($contractid);
            if(empty($newincome)) {
                $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
                $num = $manageEntity->inc;
                $num < 10 && $num = "0" . $num;
                $incomecode = $manageEntity->contract_code . "-SR-" . $num; // 生成收入项编码

                $newincome = new ContractRevenueEntity();
                $newincome->revenue_id = StringHelper::uuid();
                $newincome->contract_id = $contractid;
                $newincome->contract_payover_id = $item->contract_payover_id;
                $newincome->income_code = $incomecode;
                $newincome->created_on = ConfigEntity::getDbNowDate();
            }
            $newincome->revenue_type = $this->getBussAccountTypesId($manageEntity->business_type_id,$item->application_name);
            $newincome->amount = $item->balance_amount;
            $newincome->carryover_begin_time = $item->authorize_time;
            if(empty($item->begin_time)) {
                $newincome->right_begin_time = $item->authorize_time;
            }else{
                $newincome->right_begin_time = $item->begin_time;
            }
            if(empty($item->end_time)) {
                $newincome->right_end_time = date('Y-m-d H:i:s',strtotime("+".round($item->authorize_period)." months", strtotime($item->authorize_time)));;
            }else{
                $newincome->right_end_time = $item->end_time;
            }
            $newincome->wait_confirm_amount = $item->balance_amount;
            $newincome->modified_on = ConfigEntity::getDbNowDate();
            $newincome->remark = '结算与返款界面保存数据时同步生成';
            $check = $newincome->generateCheck(empty($before)?ContractRevenueEntity::OPERATE_ADD:ContractRevenueEntity::OPERATE_EDIT);
            if(!$check){
                throw new \Exception(empty($before)?'待生成的收入项不满足生成条件':'待修改的收入项不满足修改条件');
            }
            $res = $newincome->save();
            $now = $newincome?$newincome->getAttributes():false;
            if(empty($before)){
                IncomeItemLogRepository::add($before,$now,$res,IncomeItemLogRepository::OPERATE_ADD);
            }else{
                IncomeItemLogRepository::add($before,$now,$res,IncomeItemLogRepository::OPERATE_EDIT);
            }
            $manageEntity->save();

            if(!empty($erpcontractid) && YII_ENV_PROD){
                //保存完成后调用EKP接口
                $params = [
                    'ContractGuid'=>$erpcontractid, //终端合同GUID GUID
                    'ErpContractCode'=>$erpcontractcode,
                    'SrGuid'=>$newincome->revenue_id,
                    'SrCode'=>$newincome->income_code, // 进货合同收入项编号 字符串
                    'SrName'=>BussAccountTypesRepository::getRevenueTypeNameById($newincome->revenue_type), //收入项名称 字符串
                    'BeginDate'=>$newincome->carryover_begin_time, //收入开始日期 日期
                    'JsAmount'=>$balanceamount, //进货合同结算金额 浮点型
                    'SrAmount'=>$newincome->amount, //本次产生收入项金额 浮点型
                    'BeginOn'=>$newincome->right_begin_time, //权益开始日期
                    'EndOn'=>$newincome->right_end_time, //权益结束日期
                    'Source'=>'yl', //来源 字符串 yk/yl/ykj
                    'OperationUserGuid'=>Yii::$app->user->getIdentity()->userguid, //操作人GUID GUID
                    'OperationDate'=>ConfigEntity::getDbNowDate() //操作时间 日期
                ];

                $this->EkpIncomeSync($params);
            }
        }
    }

    private function EkpIncomeSync($params){
        $erpinterface = new ErpInterfaceService();
        $result = $erpinterface->EkpIncomeSync($params);
        return $result;
    }

    //根据产品名称获取合同核算类型确认方式
    public static function getBussAccountTypesId($busstypeid, $appname){
        if(empty($appname)){
            return '';
        }

        if($busstypeid == 'f8592797-54ca-11e7-9f96-000c29310f8b' || $busstypeid =='f854fa59-54ca-11e7-9f96-000c29310f8b'){
            $acctypeid = 'a7e81732-3d27-45ea-b056-929fe9ed9f1d';    //开发商线下活动\供应商线下活动
        }elseif($busstypeid == 'f851bc86-54ca-11e7-9f96-000c29310f8b' || $busstypeid == 'f85729eb-54ca-11e7-9f96-000c29310f8b'){
            $acctypeid = 'a8d08aa9-baad-4279-bbe1-1d05852b9e38';    //云采购采宝、供应商考察报告
        }elseif($busstypeid == 'f85342fe-54ca-11e7-9f96-000c29310f8b'){
            $acctypeid = '51a24c9f-7338-11e7-aa68-2c44fd7fa0a8';    //云采购会员
        }elseif($busstypeid  == '9a96f3dc-54ca-11e7-9f96-000c29310f8b' || $busstypeid=='f85b3855-54ca-11e7-9f96-000c29310f8b'){
            if(strpos($appname,'移动验房') === false && strpos($appname,'短信') === false){   //saas产品
                $acctypeid = '8fd17068-5eb4-4588-816d-8376bba2caf7';
            }else{
                $acctypeid = 'a8d08aa9-baad-4279-bbe1-1d05852b9e38';
            }
        }else{
            $acctypeid = 'a8d08aa9-baad-4279-bbe1-1d05852b9e38';       //查找不到的按照一次性处理
        }

        return $acctypeid;
    }

    private function getContractBalanceAmountTotal($applications)
    {
        $result = 0;
        foreach ($applications as $application) {
            $result += floatval($application['balance_amount']);
        }

        return $result;
    }

    /**
     * 获取结算与返款信息数据
     * @param string $contractId 合同Id
     * @return \common\entities\myhtsq\ContractManageEntity
     */
    public function getContractBalanceInfo($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        $data = [];
        $data['contract'] = $contractModel;
        $data['applications'] = ContractApplicationRepository::getAllContractApplicationByContractId($contractId);
        return $data;
    }

    /**
     * 获取合同开通信息
     * @param string $contractId 合同id
     * @return array
     */
    public function getContractOrganizationInfo($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }

        $contract_repository = new MyscrmContractRepository();
        $contractInfo = $contract_repository->getContractByContractNum($contractModel->contract_code); //获取合同表信息

        if (empty($contractInfo)) {
            return [];
        }
        $organizationId = $contractInfo->OrganizationId;
        $data['beginOn'] = $contractInfo->BeginOn;
        $data['endOn'] = $contractInfo->EndOn;
        $data['organizationId'] = $contractInfo->OrganizationId;

        $organizationInfo = MyscrmOrganizationRepository::getById($organizationId);
        if (!empty($organizationInfo)) {
            $data['uniqueName'] = $organizationInfo->UniqueName; //企业号
            $data['friendlyName'] = $organizationInfo->FriendlyName; //企业名称
        } else {
            $data['uniqueName'] = ''; //企业号
            $data['friendlyName'] = ''; //企业名称
        }

        //授权列表
        $authorizeList = OrganizationToAuthorizeRepository::getAuthorizeListByOrganizationId($organizationId, $contractInfo->ContractId);
        if (empty($authorizeList)) {
            $authorizeList = [];
        } else {
            $authorize = [];
            foreach ($authorizeList as $key => $value) {
                $authorize[$key]['totalNum'] = $value->TotalNum; //授权总数
                $applicationInfo = MyscrmApplicationRepository::getApplicationByApplicationId($value->ApplicationId);
                if (empty($applicationInfo)) {
                    $authorize[$key]['applicationName'] = '';
                } else {
                    $authorize[$key]['applicationName'] = $applicationInfo->FriendlyName;
                }
            }

            $authorizeList = $authorize;
        }
        $data['AuthorizeList'] = $authorizeList;

        $data['specialAuthorize'] = SpecialApprovalAuthorizeRepository::getSpecialApprovalAuthorizeByContractCode($contractInfo->ContractNum);

        return $data;
    }

    /**
     * 获取合同性质
     * @return array
     */
    public function getContractNatures()
    {
        return ContractPropertyRepository::getAllContractProperty();
    }

    /**
     * 根据性质id,获取帐套公司列表
     * @param string $propertyId 性质id
     * @return array
     */
    public function getContractAccountCompanyList($propertyId)
    {
        return ContractAccountCompanyRepository::getContractAccountCompanyListByPropertyId($propertyId);
    }

    /**
     * 根据性质id,获取签署公司列表
     * @param string $propertyId 性质id
     * @return array
     */
    public function getContractCompanyList($propertyId)
    {
        return ContractCompanyRepository::getContractCompanyListByPropertyId($propertyId);
    }

    /**
     * 获取合同类别
     * @return array
     */
    public function getContractCategories()
    {
        return ContractCategoryRepository::getAllContractCategory();
    }

    /**
     * 获取合同大类
     * @return array
     */
    public function getContractBigClass()
    {
        return ContractBigCategoryRepository::getAllContractBigClass();
    }

    /**
     * 根据大类id,获取合同小类
     * @param string $bigClassId 合同大类
     * @return array
     */
    public function getContractSmallClass($bigClassId)
    {
        return ContractLittlerCategoryRepository::getAllContractLittlerCategoryByBigClassId($bigClassId);
    }

    /**
     * 根据关键字，获取产品名称列表
     * @param string $keyword 关键字
     * @param int $limit 返回条数 传空：则全部返回
     * @return array
     */
    public function getProducts($keyword, $limit)
    {
        $dataList = ApplicationInfoRepository::getApplicationInfoByKeyword($keyword, $limit);
        $data = [];
        if (!empty($dataList)) {
            foreach ($dataList as $key => $value) {
                $data[$key] = $value->attributes;
                //$data[$key]['applicationPrices'] = ApplicationPriceRepository::getAllApplicationPriceByApplicationId($value->application_id); //获取产品价格列表
            }
        }

        return $data;
    }

    /**
     * 根据关键字，获取应收款名称列表
     * @param string $keyword 关键字
     * @return array
     */
    public function getReceivableFundName($keyword)
    {
        return ReceivableItemRepository::getReceivableItemByKeyword($keyword);
    }

    /**
     * 获取款项小类
     * @param string $propertyId 性质id
     * @return array
     */
    public function getFundSmallClass($propertyId)
    {
        return MoneyCategoryItemRepository::getAllMoneyCategoryItemListByPropertyId($propertyId);
    }

    /**
     * 获取所有核算类型
     */
    public function getBussAccountTypes()
    {
        return BussAccountTypesRepository::getAllBussAccountTypes();
    }

    /**
     * 特批授权界面获取合同select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $orgId 租户Id
     * @param string $limit 只显示几条记录
     */
    public static function getContractListForSepcialAuthorizeSelect2($keyword, $orgId, $limit)
    {
        return ContractManageRepository::getContractListForSepcialAuthorizeSelect2($keyword, $orgId, $limit);
    }

    /**
     * 违规合同界面获取合同select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $limit 只显示几条记录
     */
    public static function getContractListForViolatedContractSelect2($keyword, $limit)
    {
        return ContractManageRepository::getContractListForViolatedContractSelect2($keyword, $limit);
    }

    /**
     * 获取合同文档信息
     * @param string $contractId 合同id
     * @return array
     */
    public function getContractDocuments($contractId)
    {
        $data['file'] = DocumentRepository::getDocumentListByBusinessId($contractId); //上传文件列表
        $data['contractDocuments'] = ContractDocumentRepository::getContractDocumentListByContractId($contractId); //文档信息列表
        return $data;
    }

    /**
     * 保存合同文档信息
     * @param string $contractId 合同id
     * @param array $files 文件数组
     * @param array $documents 文档信息数组
     * @return boolean
     */
    public function saveContractDocuments($contractId, $files, $documents)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }

        //处理保存文件
        if (!empty($files) && is_array($files)) {

            foreach ($files as $value) {
                if (!isset($value ['__type'])) {
                    $value ['__type'] = 'update';
                }
                switch ($value ['__type']) {
                    case 'delete' :
                        DocumentRepository::delDocumentById($value ['document_id']);
                        break;
                    case 'add' :
                        $documentModel = new DocumentModel ();
                        $documentModel->setAttributes($value);
                        $documentModel->created_on = ConfigEntity::getDbNowDate();
                        $explode = explode('.', $value['document_name']);
                        $extName = end($explode);
                        $documentModel->document_ext_name = $extName;
                        $documentModel->business_id = $contractId;
                        if ($documentModel->validate()) {
                            $newdoc = new DocumentRepository();
                            $newdoc->addDocument($documentModel);
                        }
                        break;
                }
            }
        }


        // 处理保存文档信息
        if (!empty($documents) && is_array($documents)) {
            foreach ($documents as $value) {
                if (!isset($value ['__type'])) {
                    $value ['__type'] = 'update';
                }
                switch ($value ['__type']) {
                    case 'delete' :
                        ContractDocumentRepository::deleteContractDocumentByContractIdAndDocumentId($contractId, $value ['document_id']);
                        break;
                    case 'add' :
                        $contractDocument = new ContractDocumentModel ();
                        $contractDocument->setScenario('add');
                        $contractDocument->load($value, '');
                        if ($contractDocument->validate()) {
                            $contractDocument->contract_id = $contractId;
                            ContractDocumentRepository::addContractDocument($contractDocument); // 新增合同文档信息
                        }
                        break;
                    case '' :
                    case 'update' :
                        $contractDocument = new ContractDocumentModel ();
                        $contractDocument->setScenario('update');
                        $contractDocument->load($value, '');
                        if ($contractDocument->validate()) {
                            ContractDocumentRepository::updateContractDocument($contractDocument); // 新增合同文档信息
                        }
                        break;
                }
            }
        }

        return true;
    }

    /**
     * 获取业绩信息
     * @param string $contractId 合同id
     * @return array 返回业绩信息数组数据
     */
    public function getSignAchievement($contractId)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }

        $r_data['contract_id'] = $contractModel->contract_id; //合同id
        $r_data['contract_deal_discount'] = $contractModel->contract_deal_discount; //合同成交折扣
        $r_data['draw_project_numeric'] = $contractModel->draw_project_numeric; //提成项目数
        $r_data['project_numeric'] = $contractModel->project_numeric; //提成项目数
        $r_data['contract_property_name'] = ContractPropertyRepository::getPropertyNameByPropertyId($contractModel->contract_property_id); //获取性质名称

        $r_data['signAchievements'] = SignAchievementRepository::getSignAchievementListByContractId($contractId); //根据合同id,获取签约业绩

        foreach ($r_data['signAchievements'] as $key => $val) {
            $r_data['signAchievements'][$key]['belong_name'] = $this->getUserNameById($val['belong_by']); //获取归属人名称
            $r_data['signAchievements'][$key]['manager_name'] = $this->getUserNameById($val['manager_by']); //获取ERP客户经理名称
            $r_data['signAchievements'][$key]['area_name'] = $this->getBuNameById($val['area_by']); //获取区域名称
            $r_data['signAchievements'][$key]['department_name'] = $this->getBuNameById($val['department_by']); //获取部门名称

            $r_data['signAchievements'][$key]['erp_achievement_belong_name'] = $this->getUserNameById($val['erp_achievement_belong']);//获取ERP归属人名称
            $r_data['signAchievements'][$key]['erp_achievement_belong_abu_name'] = $this->getBuNameById($val['erp_achievement_belong_abu']); //获取ERP业绩归属ABU
            $r_data['signAchievements'][$key]['erp_achievement_belong_abu_owner_name'] = $this->getUserNameById($val['erp_achievement_belong_abu_owner']); //获取ERP归属ABU负责人
            $r_data['signAchievements'][$key]['erp_achievement_belong_bu_manager_name'] = $this->getUserNameById($val['erp_achievement_belong_bu_manager']); //获取ERP归属部门经理
            $r_data['signAchievements'][$key]['erp_achievement_belong_bu_name'] = $this->getBuNameById($val['erp_achievement_belong_bu']); //获取ERP业绩归属部门
        }

        $r_data['paymentAchievement'] = PaymentAchievementRepository::getPaymentAchievementListByContractId($contractId); //根据合同id,获取回款业绩
        foreach ($r_data['paymentAchievement'] as $key => $val) {
            $r_data['paymentAchievement'][$key]['receivable_item_name'] = ReceivableItemRepository::getReceivableItemNameByItemId($val['receivable_item_id']);//获取款项名称
            $r_data['paymentAchievement'][$key]['money_category_item_name'] = MoneyCategoryItemRepository::getMoneyCategoryItemNameByItemId($val['money_category_item_id']);//获取款项小类名称

            $r_data['paymentAchievement'][$key]['belong_name'] = $this->getUserNameById($val['belong_by']); //获取归属人名称
            $r_data['paymentAchievement'][$key]['manager_name'] = $this->getUserNameById($val['manager_by']); //获取ERP客户经理名称
            $r_data['paymentAchievement'][$key]['area_name'] = $this->getBuNameById($val['area_by']); //获取区域名称
            $r_data['paymentAchievement'][$key]['department_name'] = $this->getBuNameById($val['department_by']); //获取部门名称

            $r_data['paymentAchievement'][$key]['erp_achievement_belong_name'] = $this->getUserNameById($val['erp_achievement_belong']);//ErpUserRepository::getUserNameByBuguid($val['erp_achievement_belong']); //获取ERP归属人名称
            $r_data['paymentAchievement'][$key]['erp_achievement_belong_abu_name'] = $this->getBuNameById($val['erp_achievement_belong_abu']); //获取ERP业绩归属ABU
            $r_data['paymentAchievement'][$key]['erp_achievement_belong_abu_owner_name'] = $this->getUserNameById($val['erp_achievement_belong_abu_owner']); //获取ERP归属ABU负责人
            $r_data['paymentAchievement'][$key]['erp_achievement_belong_bu_manager_name'] = $this->getUserNameById($val['erp_achievement_belong_bu_manager']); //获取ERP归属部门经理
            $r_data['paymentAchievement'][$key]['erp_achievement_belong_bu_name'] = $this->getBuNameById($val['erp_achievement_belong_bu']); //获取ERP业绩归属部门
        }

        return $r_data;
    }

    /**
     * 保存业绩修改
     * @param string $contractId 合同id
     * @param int $drawProjectNumeric 提交项目数
     * @param array $signAchievements 签约业绩列表数组
     * @param array $paymentAchievements 回款业绩列表
     * @param string $achievementRemark 业绩备注
     * @return array
     */
    public function saveSignAchievement($contractId, $drawProjectNumeric, $signAchievements, $paymentAchievements, $projectNumeric = 0, $achievementRemark)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($contractId); // 获取model
        if (empty($contractModel)) { // 合同不存在
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_NOT_EXISTS);
        }
        $contractModel->draw_project_numeric = $drawProjectNumeric;
        $contractModel->project_numeric = $projectNumeric;
        $contractModel->achievement_remark = $achievementRemark;
        $contractModel->save();


        if (!empty($signAchievements)) {
            foreach ($signAchievements as $value) {
                // 处理签约业绩信息
                if (!isset($value ['__type'])) {
                    $value ['__type'] = 'update';
                }
                switch ($value ['__type']) {
                    case 'delete' :
                        SignAchievementRepository::deleteSignAchievementByAchievementId($value['achievement_id']); //删除签约业绩
                        break;
                    case 'add' :
                        $signAchievementModel = new SignAchievementModel();
                        $signAchievementModel->setScenario('add');
                        $signAchievementModel->load($value, '');
                        $signAchievementModel->contract_id = $contractId;
                        if ($signAchievementModel->validate()) {
                            SignAchievementRepository::addSignAchievement($signAchievementModel); // 新增签约业绩
                        }
                        break;
                    case '' :
                    case 'update' :
                        $signAchievementModel = new SignAchievementModel ();
                        $signAchievementModel->setScenario('update');
                        $signAchievementModel->load($value, '');
                        $signAchievementModel->contract_id = $contractId;
                        if ($signAchievementModel->validate()) {
                            SignAchievementRepository::updateSignAchievement($signAchievementModel); // 更新签约业绩
                        }
                        break;
                }
            }
        }

        // 处理回款业绩信息
        if (!empty($paymentAchievements)) {
            foreach ($paymentAchievements as $value) {
                if (!isset($value ['__type'])) {
                    $value ['__type'] = 'update';
                }
                switch ($value ['__type']) {
                    case 'delete' :
                        PaymentAchievementRepository::deletePaymentAchievementByAchievementId($value['achievement_id']); //删除回款业绩
                        break;
                    case 'add' :
                        $paymentAchievementModel = new PaymentAchievementModel ();
                        $paymentAchievementModel->setScenario('add');
                        $paymentAchievementModel->load($value, '');
                        $paymentAchievementModel->contract_id = $contractId;
                        if ($paymentAchievementModel->validate()) {
                            PaymentAchievementRepository::addPaymentAchievement($paymentAchievementModel); // 新增回款业绩
                        }
                        break;
                    case '' :
                    case 'update' :
                        $paymentAchievementModel = new PaymentAchievementModel ();
                        $paymentAchievementModel->setScenario('update');
                        $paymentAchievementModel->load($value, '');
                        $paymentAchievementModel->contract_id = $contractId;
                        if ($paymentAchievementModel->validate()) {
                            PaymentAchievementRepository::updatePaymentAchievement($paymentAchievementModel); // 更新回款业绩
                        }
                        break;
                }
            }
        }

        return true;
    }

    /**
     * 获取最新合同编号
     * @param string $areaCode 区域代码
     * @param string $customerId 客户id
     * @param string $contractCode 合同编号
     * @return string
     */
    public function getContractFlowCode($areaCode, $customerId, $contractCode)
    {
        $maxContractFlowCode = ContractFlowCodeRepository::getMaxContractFlowCode() + 1;

        return ContractFlowCodeRepository::createContractCode($areaCode, $customerId, $maxContractFlowCode, $contractCode);
    }

    /**
     * 导出合同
     * @param boolean $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $beginDate 结算开始时间
     * @param string $endDate 结算结束时间
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @return array
     */
    public function exportContract($status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null, $exporttype = '',$businesstype = '')
    {
        $objPHPExcel = new \PHPExcel();
        $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);

        #区域过滤（不是“我的合同”）
        if (empty($areaId) && empty($signPeopleId)) {
            $areaId = self::filterBusinessUnit(\Yii::$app->user->identity);
        }

        // 1、合同列表
        if ($exporttype == '合同基本信息' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_HT)) {
            $this->exportContractExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
        // 2、产品列表
        if ($exporttype == '产品线明细' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_CP)) {
            $this->exportContractProductExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
        // 3、结算与返款信息列表
        if ($exporttype == '结算与返款' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_CP)) {
            $this->exportContractBalanceExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
        // 4、收入列表
        if ($exporttype == '收入' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_SR)) {
            $this->exportContractRevenueExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
        // 5、应收列表
        if ($exporttype == '应收' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_YS)) {
            $this->exportContractReceivableExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
        // 6、发票列表
        if ($exporttype == '发票' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_FP)) {
            $this->exportContractInvoiceExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
        // 7、回款列表
        if ($exporttype == '回款' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_HK)) {
            $this->exportContractPaymentExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
        //8、开通信息
        if ($exporttype == '开通信息' && RoleService::checkLoginUserAccess(ActionCode::CONTRACT_CP)) {
            $this->exportContractProductKtExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
        }
//        // 7、签约业绩列表
//        if (RoleService::checkLoginUserAccess(ActionCode::CONTRACT_QSYJ)) {
//            $this->exportContractSignAchievementExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId);
//            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
//        }
//        // 8、回款业绩列表
//        if (RoleService::checkLoginUserAccess(ActionCode::CONTRACT_HKYJ)) {
//            $this->exportContractPaymentAchievementExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId);
//            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
//        }
//        // 9、合同文档列表
//        if (RoleService::checkLoginUserAccess(ActionCode::CONTRACT_WD)) {
//            $this->exportContractDocumentExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId);
//            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
//        }
//        // 10、违规合同列表
//        if (RoleService::checkLoginUserAccess(ActionCode::CONTRACT_WGHT)) {
//            $this->exportContractViolatedExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId);
//            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
//        }
//        // 11、特批发票列表
//        if (RoleService::checkLoginUserAccess(ActionCode::CONTRACT_TPFP)) {
//            $this->exportContractSpecialInvoiceExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId);
//            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
//        }
//        // 12、特批授权列表
//        if (RoleService::checkLoginUserAccess(ActionCode::CONTRACT_TPSQ)) {
//            $this->exportContractSpecialAuthorizeExecl($objPHPExcel, $status, $property, $keyword, $areaId, $signPeopleId);
//            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";LINE=" . __LINE__);
//        }

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="合同清单' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
//        $fileName = sprintf("hetong-data_%s.xls", \Yii::$app->user->identity->userguid);
//
//        // "hetong-data.xls";
//        if (!is_dir(\Yii::getAlias("@mybackend/web/xls/"))) {
//            $mkResult = mkdir(\Yii::getAlias("@mybackend/web/xls/"), 0755);
//            $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";mkResult=" . $mkResult . ";LINE=" . __LINE__);
//        }
//
//        $objWriter->save('xls/' . $fileName); //脚本方式运行，保存在当前目录
//        $filepath = \Yii::getAlias("@mybackend/web/xls/") . $fileName;
//        $key = $fileName;
//        OSS::upload($key, $filepath);
//        $ossUrl = OSS::getUrl($key);
//        $this->_errorLog->log(date('Y-m-d H:i:s') . ";time=" . time() . ";uploadResult=" . $ossUrl . ";LINE=" . __LINE__);
//        CacheManage::setExportContract($ossUrl, 864000);
//        return $ossUrl;
    }

    /**
     * 导出釆宝类合同
     * @param $beginInputDate
     * @param $endInputDate
     */
    public function exportContractCaibao($beginInputDate, $endInputDate){
        $objPHPExcel = new \PHPExcel();

        $this->exportContractCaibaoExecl($objPHPExcel, $beginInputDate, $endInputDate);

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="合同清单' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 导出釆宝类充值明细
     * @param $contract_id
     */
    public function exportContractCaibaoMx($contract_id){
        $objPHPExcel = new \PHPExcel();

        $this->exportContractCaibaoExeclMx($objPHPExcel, $contract_id);

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="充值明细清单' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 导出釆宝信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     * 参考：\common\services\myhtsq\ContractService\getContractInfo->ContractApplicationRepository::getAllContractApplicationByContractId
     */
    private function exportContractCaibaoExecl($objPHPExcel, $beginInputDate, $endInputDate)
    {
        $data = ContractManageRepository::getContractCaibaoList('', $beginInputDate, $endInputDate,'export');
        $data = $data['items'];

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('釆宝');

        //设置列标题
        $columnTitles = ['序号','合同信息','生效日期','期初采宝余额','本月充值总额','本月消耗总额','期末采宝余额'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $j-1); //序号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同信息
                $i++;
                $activeSheet->setCellValue($i . $j, $val['input_date']); //生效日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['begin_remain_amount']); //期初采宝余额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['this_month_recharge_amount']); //本月充值总额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['this_month_consume_amount']); //本月消耗总额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['end_remain_amount']); //期末采宝余额

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列
    }

    /**
     * 导出釆宝充值明细信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     * 参考：\common\services\myhtsq\ContractService\getContractInfo->ContractApplicationRepository::getAllContractApplicationByContractId
     */
    private function exportContractCaibaoExeclMx($objPHPExcel, $contract_id)
    {
        $data = ContractManageRepository::getContractCaibaoListmx('', $contract_id,'export');
        $data = $data['items'];

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('釆宝充值明细');

        //设置列标题
        $columnTitles = ['序号','用户名','公司名称','充值金额','支付时间'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $j-1); //序号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['user_name']); //用户名
                $i++;
                $activeSheet->setCellValue($i . $j, $val['company_name']); //公司名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['pay_amount']); //充值金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['pay_time']); //时间

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列
    }

    public function exportContractCaibaoDetail($contractid){
        $objPHPExcel = new \PHPExcel();

        $this->exportContractCaibaoDetailExecl($objPHPExcel, $contractid);

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="釆宝明细' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    public function exportCaibaoInvoice($contractid){
        $objPHPExcel = new \PHPExcel();

        $this->exportCaibaoInvoiceExecl($objPHPExcel, $contractid);

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="釆宝明细' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    private function exportContractCaibaoDetailExecl($objPHPExcel,$contractid){
        $data = ContractManageRepository::getContractCaibaoDetailList($contractid);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('釆宝明细');

        //设置列标题
        $columnTitles = ['序号','用户名','公司名称','消耗金额','余额'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $j-1); //序号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['user_name']); //用户名
                $i++;
                $activeSheet->setCellValue($i . $j, $val['company_name']); //公司名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['consume_amount']); //消耗金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance']); //余额

                $j++;
            }
        }
    }

    private function exportCaibaoInvoiceExecl($objPHPExcel,$contractid){
        $data = ContractManageRepository::getContractCaibaoInvoice($contractid);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('釆宝明细');

        //设置列标题
        $columnTitles = ['序号','发票代码','发票编号','开票金额','开票单位','客户名称','开票时间','发票类别','发票类型'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $j-1); //序号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_code']); //发票代码
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_no']); //发票编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_amount']); //开票金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['BUName']); //开票单位
                $i++;
                $activeSheet->setCellValue($i . $j, $val['UserName']); //客户名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_date']); //开票时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_category']); //发票类别
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_type']); //发票类型

                $j++;
            }
        }
    }

    /**
     * 租期即将到期授权提醒
     * @param $expiredDays 过期天数：30、60
     * @return array|\yii\db\ActiveRecord[]
     */
    public function authorizationExpiredRemind($expiredDays)
    {
        $expiredDate = date_add(date_create_from_format('Y-m-d H:i:s', ConfigEntity::getDbNowDate()), \DateInterval::createFromDateString($expiredDays . ' Day'));
        $expiredDate = date_format($expiredDate, 'Y-m-d');
        $expiredAuthorizations = ContractManageRepository::getAuthorizationExpiredRemind($expiredDate);
        foreach ($expiredAuthorizations as $key => $item) {
            //获取合同信息
            $contractInfo = ContractManageRepository::getContractManageModelByContractId($item['contract_id']);
            $emailParams = [
                'contractId' => $contractInfo->contract_code,
                'custName' => $contractInfo->customer_name,
                'custFullName' => $contractInfo->customer_full_name,
                'signAmount' => $contractInfo->sign_amount,
                'uniqueName' => $item['UniqueName'],
                'period' => date('Y-m-d', strtotime($item['BeginOn'])) . '至' . date('Y-m-d', strtotime($item['EndOn']))
            ];
            $apps = ContractManageRepository::getContractApps($item['ContractId']);
            if (empty($apps)) {
                $apps = [];
            }
            $strapps = '';
            foreach ($apps as $appkey => $appitem) {
                $strapps .= $appitem['FriendlyName'] . ':' . $appitem['TotalNum'] . ';';
            }

            $emailParams['apps'] = $strapps;
            $this->sendEmailForAuthorizeExpired($item['sign_people_id'], '【合同管理】租期到期提醒', 'authorizeExpired', $emailParams, ['fuxl@mysoft.com.cn' => '付小玲']);
        }

    }

    /**
     * erp获取合同信息
     * @param string $propertyId 合同性质ID
     * @param date|null $startReviewDate 开始审核日期（date|null:date:给定日期以后审核的数据，null：所有审核的合同数据）
     * @param int $page 取数页码,default=1
     * @param int $pageSize 分页大小,default=20
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getContractsForERP($propertyId, $startReviewDate, $page = 1, $pageSize = 20)
    {
        return ContractManageRepository::getContractsForERP($propertyId, $startReviewDate, $page, $pageSize);
    }

    /**
     * 获取当前活动表格
     * @param type $objPHPExcel
     * @return type
     */
    private static function getActiveSheet($objPHPExcel)
    {
        if (self::$sheetIndex == 0) {
            $objPHPExcel->setActiveSheetIndex(self::$sheetIndex);
            $activeSheet = $objPHPExcel->getActiveSheet();
        } else {
            $activeSheet = $objPHPExcel->createSheet(self::$sheetIndex);
        }
        self::$sheetIndex++;
        return $activeSheet;
    }

    private function getTenantInfo($data)
    {
        $tenant_list = TenantService::getContractTenantList();
        $tenant_list_mapping_list = [];
        foreach ($tenant_list as $tenant) {
            $tenant_list_mapping_list[$tenant['contract_code']] = $tenant;
        }

        $result = [];
        foreach ($data as $contract) {
            if (key_exists($contract['contract_code'], $tenant_list_mapping_list)) {
                $tenant = $tenant_list_mapping_list[$contract['contract_code']];
                if (isset($tenant)) {
                    $contract['BeginOn'] = $tenant['rental_start'];
                    $contract['EndOn'] = $tenant['rental_end'];
                }
            } else {
                $contract['BeginOn'] = '';
                $contract['EndOn'] = '';
            }

            $result[] = $contract;
        }

        return $result;
    }

    /**
     * 导出合同
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     * 参考：\common\services\myhtsq\ContractService\getContractList
     */
    private function exportContractExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null)
    {
        $data = ContractManageRepository::getContractListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
        $data = $this->getTenantInfo($data);
        //$data = $this->getContractApplicationBalance($data);
        //$data = $this->setPaymentAmount($data, $status, $property, $keyword, $areaId, $signPeopleId);

        $this->makePartData($data);
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('合同');



        //设置列标题
        $columnTitles = [
            //'合同GUID',
            '客户简称',
            '顶级客户简称',
            '签约客户全称',
            '合同编号',
            '关联ERP合同编号',
            '关联会签合同编号',
            '账套公司',
            '合同性质',
            '合同来源（业财）',
            '合同来源（财务）',
            '合同类别',
            '合同签署公司',
            '合同所属区域',
            '签约人',
            '签约日期',
            '录入日期',
            '生效日期',//新
            '客户类别',//新
            '签约金额',
            '已回款金额',
            '租用金额',
            '交付金额',
            '应结算金额',
            '已结算金额',
            '返款金额',
            '是否具备返款条件',//是否具备结算条件
            '结算状态',
            '账号开通时间（第一次）',
            '租期开始时间',
            '租期结束时间',
            '业务类型',
            '签约产品',
            '供应商名称'
        ];
        //设置单元格的值
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }


        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['contract_id']); // 合同GUID
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['top_customer_name']); //顶级客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //签约客户全称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_contract_code']); //关联ERP合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, ''); //关联会签合同编号,暂时没有字段,后补
                $i++;
                $accountCompayName = ContractAccountCompanyRepository::getContractAccountCompanyListByPropertyId($val['contract_property_id']);
                $activeSheet->setCellValue($i . $j, empty($accountCompayName) ? '' : $accountCompayName[0]->account_company_name); //账套公司
                $i++;
                //$propertyName = ContractPropertyRepository::getPropertyNameByPropertyId($val['contract_property_id']);
                //$activeSheet->setCellValue($i . $j, $propertyName === FALSE ? '' : $propertyName); //合同性质
                $activeSheet->setCellValue($i . $j, $val['property_name'] === FALSE ? '' : $val['property_name']); //合同性质
                $i++;
                $activeSheet->setCellValue($i . $j, $val['soure_business']); //合同来源（业财）
                $i++;
                $activeSheet->setCellValue($i . $j, $val['soure_financial']); //合同来源（财务）
                $i++;
                $categoryName = ContractCategoryRepository::getCategoryNameByCategoryId($val ['category_id']);
                $activeSheet->setCellValue($i . $j, $categoryName === FALSE ? '' : $categoryName); //合同类别
                $i++;
                $companyName = ContractCompanyRepository::getContractCompanyNameByCompanyId($val ['company_id']);
                $activeSheet->setCellValue($i . $j, $companyName === FALSE ? '' : $companyName); //合同签署公司
                $i++;
                $areaName = ErpBusinessUnitRepository::getBunameByBuguid($val ['area_id']);
                $activeSheet->setCellValue($i . $j, $areaName === FALSE ? '' : $areaName); //合同所属区域
                $i++;
                $signName = ErpUserRepository::getUserNameByBuguid($val ['sign_people_id']);
                if(empty($signName)){
                    $signName = $val['sign_people_name'];
                }
                $activeSheet->setCellValue($i . $j, $signName === FALSE ? '' : $signName); //签约人
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['sign_date'])); //签约日期
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['input_date'])); //签约日期
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['effect_date'])); //生效日期日期
                $i++;
                $activeSheet->setCellValue($i . $j, empty($val['customer_property']) ? '开发商' : '供应商'); //客户类别
                $i++;
                $activeSheet->setCellValue($i . $j, $val['sign_amount']); //签约金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_amount']); //已回款金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['rent_amount']); //租用金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['delivery_amount']); //交付金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_should_amount']); //应结算金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_amount']); //已结算金额
                $i++;
                //明源签约-直属 联营签约-云链结算 返款为0
                $empty_back_amount = in_array($val['contract_property_id'], ['54f8a2b7-fce7-11e4-bed8-00155d02c832', '7f856e81-fce8-11e4-bed8-00155d02c832']);
                $activeSheet->setCellValue($i . $j, $empty_back_amount ? 0 : $val['back_amount']); //返款金额
                $i++;

                $activeSheet->setCellValue($i . $j, $this->getPaymentCondition($val['business_type_id'],$val['contract_property_id'],$val['sign_amount'],$val['back_amount'])); //是否具备返款条件
                $i++;
//                $activeSheet->setCellValue($i . $j, $this->getBalanceCondition($val['business_type_id'],$val['contract_property_id'],$val['contract_id'])); //是否具备结算条件
//                $i++;
                $activeSheet->setCellValue($i . $j, '未结算'); //结算状态
                $i++;
                $activeSheet->setCellValue($i . $j, $this->getContractFirstRightBeginTime($val['contract_id'])); //账号开通时间（第一次）
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['BeginOn']));//租期开始时间
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['EndOn']));//租期结束时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_name']);//业务类型
                $i++;
                $activeSheet->setCellValue($i . $j, $this->getContractProductNames($val['contract_id']));//签约产品
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_id']=='f854fa59-54ca-11e7-9f96-000c29310f8b'?$val['activity_name']:$val['supplier_name']);//供应商名称
                $j++;
            }
        }

        // 区域销售角色隐藏对应列
        if (RoleService::checkOnlyOneRole(\Yii::$app->user->identity->userguid, RoleCode::AREA_SALE)) {
            $activeSheet->getColumnDimension('Q')->setVisible(false); //结算金额
            //$activeSheet->getColumnDimension('Q')->setVisible(false); //返款金额
            //$activeSheet->getColumnDimension('U')->setVisible(false); //结算状态
        }
    }

    private function getPaymentCondition($busstypeid,$propertyid,$signamount,$backamount){
        if(strpos('f85b3855-54ca-11e7-9f96-000c29310f8b,f854fa59-54ca-11e7-9f96-000c29310f8b,9a96f3dc-54ca-11e7-9f96-000c29310f8b',$busstypeid) !== false){
            if($propertyid == 'c33eda1c-54d8-11e7-9f96-000c29310f8b' || $propertyid == 'c3402517-54d8-11e7-9f96-000c29310f8b') {
                if (floatval($signamount) == floatval($backamount)) {
                    return '是';
                }else{
                    return '否';
                }
            }
        }
        return '';
    }

    private function getBalanceCondition($busstypeid,$propertyid,$contractid){
        if($busstypeid == 'f85b3855-54ca-11e7-9f96-000c29310f8b'){
            if($propertyid == '54f8a2b7-fce7-11e4-bed8-00155d02c832' || $propertyid == '593d3a12-006a-11e5-bed8-00155d02c832'){
                if(!empty($this->getContractFirstRightBeginTime($contractid))){
                    return '是';
                }else{
                    return '否';
                }
            }
        }
        return '';
    }

    private function getContractProductNames($contractid){
        $names = '';
        $products = ContractApplicationRepository::getAllContractApplicationByContractId($contractid);
        foreach($products as $item){
            if($names == ''){
                $names = $item['application_name'];
            }else {
                $names .= ',' . $item['application_name'];
            }
        }
        return $names;
    }

    //合同下交付信息开通时间
    private function getContractFirstRightBeginTime($contractid){
        $firstTime = '';
        $data = ContractPayoverRepository::getContractPayoverInfoByContractId($contractid);
        if(!empty($data)){
            $firstTime = $data[0]['authorize_time'];
        }
        return $firstTime;
    }

    private function setPaymentAmount($data, $status, $property, $keyword, $areaId, $signPeopleId)
    {
        $result = [];
        $payment_data = ContractManageRepository::getContractPaymentListForExport($status, $property, $keyword, $areaId, $signPeopleId);
        foreach ($data as $contract) {
            $contract_id = $contract['contract_id'];
            $payment_amount = 0;
            foreach ($payment_data as $payment) {
                if ($payment['contract_id'] == $contract_id) {
                    $payment_amount += floatval($payment['payment_amount']);
                }
            }
            $contract['payment_amount'] = $payment_amount;
            $result[] = $contract;
        }

        return $result;
    }

    private function getContractApplicationBalance($data)
    {
        $contract_id_list = [];
        foreach ($data as $contract) {
            $contract_id_list[] = $contract['contract_id'];
        }

        $applications = ContractApplicationRepository::getAllContractApplicationByContractId($contract_id_list);
        $contract_application_mapping = [];
        foreach ($applications as $application) {
            $contract_id = $application['contract_id'];
            $contract_application_mapping[$contract_id][] = $application;
        }

        $result = [];
        foreach ($data as $contract) {
            $contract_id = $contract['contract_id'];
            if (array_key_exists($contract_id, $contract_application_mapping)) {
                $contract['applications'] = $contract_application_mapping[$contract_id];
                //计算产品分摊金额
                $contract['applications'] = $this->getShareAmount($contract['application_amount'], $contract['application_deal_amount'], $contract['applications']);
            } else {
                $contract['applications'] = [];
            }
            $result[] = $contract;
        }

        return $result;
    }

    /**
     * 导出合同的产品信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     * 参考：\common\services\myhtsq\ContractService\getContractInfo->ContractApplicationRepository::getAllContractApplicationByContractId
     */
    private function exportContractBalanceExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null)
    {
        $data = ContractManageRepository::getContractBalanceListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);

        //$this->makePartData($data);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('结算与返款');

        //设置列标题
        $columnTitles = ['应用名称', '开通时间', '授权数量', '结算比例', '结算金额', '签约客户全称', '合同编号', '业务类型'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['application_name']); //应用名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['authorize_time']); //开通时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['authorization_numeric']); //授权数量
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_rate']); //结算比例
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_amount']); //结算金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_name']); //业务类型

                $j++;
            }
        }
    }


    private function exportContractProductExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null){

        $data = ContractManageRepository::getContractProductListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
        $this->makePartData($data);
        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('产品线明细');

        //设置列标题
        $columnTitles = [
            '产品名称',
            '开通时间',
            '已开通数量',
            '授权标准',
            '购买数量',
            '标准总额',
            '产品租金分摊金额',
            '预测结算金额',
            '已结算金额',
            '客户简称',
            '顶级客户简称',
            '签约客户全称',
            '合同编号',
            '关联ERP合同编号',
            '关联会签合同编号',
            '账套公司',
            '合同性质',
            '合同来源（业财）',
            '合同来源（财务）',
            '合同签署公司',
            '合同所属区域',
            '签约人',
            '签约日期',
            '录入日期',
            '签约金额',
            '租金金额',
            '产品应结算金额'
        ];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['application_name']); //产品名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['authtime']); //开通时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['authnums']); //已开通数量
                $i++;
                $activeSheet->setCellValue($i . $j, $val['unit']); //授权标准
                $i++;
                $activeSheet->setCellValue($i . $j, $val['authorization_numeric']); //购买数量
                $i++;
                $activeSheet->setCellValue($i . $j, $val['amount']); //标准总额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['rent_share_amount']); //产品租金分摊金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_share_amount']); //预测结算金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balanamount']); //已结算金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['top_customer_name']); //顶级客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //签约客户全称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_contract_code']); //关联ERP合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, ''); //关联会签合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['account_company_name']); //账套公司
                $i++;
                $activeSheet->setCellValue($i . $j, $val['property_name']); //合同性质
                $i++;
                $activeSheet->setCellValue($i . $j, $val['soure_business']); //合同来源（业财）
                $i++;
                $activeSheet->setCellValue($i . $j, $val['soure_financial']); //合同来源（财务）
                $i++;
                $activeSheet->setCellValue($i . $j, $val['company_name']); //合同签署公司
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['sign_people_name']); //签约人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['sign_date']); //签约日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['input_date']); //录入日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['sign_amount']); //签约金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['rent_amount']); //租金金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_should_amount']); //产品应结算金额

                $j++;
            }
        }
    }

    private function makePartData(&$data){
        foreach($data as $key=>$value){
            if($data[$key]['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b'){
                if(!empty($data[$key]['link_contract_id'])){
                    $linkcon = ContractManageRepository::getContractManageModelByContractId($data[$key]['link_contract_id']);
                    $data[$key]['sign_people_name'] = ErpUserRepository::getUserNameByBuguid($linkcon->sign_people_id);
                    $data[$key]['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($linkcon->area_id);
                }else{
                    if($data[$key]['customer_name'] == '碧桂园房地产'){
                        $data[$key]['area_name'] = '中山公司';
                        $data[$key]['sign_people_name'] = '梁桂流';
                    }elseif($data[$key]['customer_name'] == '南京华轩'){
                        $data[$key]['area_name'] = '南京公司';
                        $data[$key]['sign_people_name'] = '张健';
                    }else {
                        $data[$key]['area_name'] = '';
                        $data[$key]['sign_people_name'] = '';
                    }
                }
            }else{
                if(empty($data[$key]['sign_people_name'])) {
                    $data[$key]['sign_people_name'] = ErpUserRepository::getUserNameByBuguid($data[$key]['sign_people_id']);
                }
                $data[$key]['area_name'] = ErpBusinessUnitRepository::getBunameByBuguid($data[$key]['area_id']);
            }
        }
    }

    /**
     * 导出合同的收入信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractRevenueExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null)
    {
        $data = ContractManageRepository::getContractRevenueListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('收入');

        //设置列标题
        $columnTitles = [
            //'收入ID', 
            '客户名称',
            '客户简称',
            '合同编号',
            '收入项编码',
            '账套公司',
            '合同性质',
            '合同类别',
            '合同小类',
            '合同所属区域',
            '核算收入类别',
            '收入项金额',
            '租期开始时间',
            '租期结束时间',
            '业务类型'
        ];
        //供应商移动工程协同增加云商城订单号
        if ($businesstype == '9a96f3dc-54ca-11e7-9f96-000c29310f8b') {
            $columnTitles[] = '订单编号';
        }
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $type_name = $val['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b'?'移动工程协同':$val['type_name'];
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['revenue_id']);
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['income_code']); //收入项编码
                $i++;
                $accountCompayName = ContractAccountCompanyRepository::getContractAccountCompanyListByPropertyId($val['contract_property_id']);
                $activeSheet->setCellValue($i . $j, empty($accountCompayName) ? '' : $accountCompayName[0]->account_company_name); //账套公司
                $i++;
                $propertyName = ContractPropertyRepository::getPropertyNameByPropertyId($val['contract_property_id']);
                $activeSheet->setCellValue($i . $j, $propertyName === FALSE ? '' : $propertyName); //合同性质
                $i++;
                $categoryName = ContractCategoryRepository::getCategoryNameByCategoryId($val ['category_id']);
                $activeSheet->setCellValue($i . $j, $categoryName === FALSE ? '' : $categoryName); //合同类别
                $i++;
                $littlerCategoryName = ContractLittlerCategoryRepository::getContractLittlerCategoryNameByLittlerCategoryId($val['littler_category_id']);
                $activeSheet->setCellValue($i . $j, $littlerCategoryName === FALSE ? '' : $littlerCategoryName); //合同小类
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $type_name);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['amount']);
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['right_begin_time']));
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['right_end_time']));
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_name']);    //业务类型
                $i++;
                if ($val['business_type_id'] == '9a96f3dc-54ca-11e7-9f96-000c29310f8b') {
                    $activeSheet->setCellValue($i . $j, $val['orderid']);    //云商城订单编号
                    $i++;
                }

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出合同的应收款项信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractReceivableExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null)
    {
        $data = ContractManageRepository::getContractReceivableListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('应收');

        //设置列标题
        $columnTitles = ['客户名称', '客户简称', '合同编号', '合同所属区域', '款项名称', '款项小类', '收入类型', '应收金额', '应收日期', '收款责任人', '已开票金额', '已收金额', '未收金额', '是否坏账', '运营关注项', '付款条件','业务类型'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['receivable_id']);
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, ErpBusinessUnitRepository::getBunameByBuguid($val['area_id'])); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['receivable_item_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['money_category_item_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['revenue_type_name']);
                $i++;

                $activeSheet->setCellValue($i . $j, $val['receivable_amount']);   //应收
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['receivable_date']));
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payee_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['billing_amount']);   //开票
                $i++;
                $activeSheet->setCellValue($i . $j, $val['received_amount']);   //已收
                $i++;
                $activeSheet->setCellValue($i . $j, $val['receivable_amount'] - $val['received_amount']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['is_bad_debt'] == 1 ? '是' : '否');
                $i++;
                $activeSheet->setCellValue($i . $j, $val['is_operation'] == 1 ? '是' : '否');
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_condition']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_name']); //业务类型
                $i++;

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出合同的发票信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractInvoiceExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null)
    {
        $data = ContractManageRepository::getContractInvoiceListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('发票');

        //设置列标题
        $columnTitles = ['客户名称', '客户简称', '合同编号', '合同所属区域', '票据代码', '票据号码', '开票金额', '开票单位', '开票时间', '客户名称', '对应回款', '已回款金额', '是否遗失', '是否红冲', '是否收据','业务类型'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['invoice_id']);
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_code']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_no']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_amount']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['BUName']);
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['invoice_date']));
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['receivables_amount']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_amount']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['is_lose'] == 1 ? '是' : '否');
                $i++;
                $activeSheet->setCellValue($i . $j, $val['is_red_invoice'] == 1 ? '是' : '否');
                $i++;
                $activeSheet->setCellValue($i . $j, $val['is_receipt'] == 1 ? '是' : '否');
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_name']);   //业务类型
                $i++;

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出合同的回款信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractPaymentExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null)
    {
        $data = ContractManageRepository::getContractPaymentListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);

        if (isset($data) && count($data) > 0) {
            foreach ($data as $k => $v) {
                $billing_invoice_no = '';
                $invoicePayments = InvoicePaymentRepository::getInoicePaymentByPaymentId($v['payment_id']);
                if (!(isset($invoicePayments) && count($invoicePayments) > 0)) {
                    $data[$k]['billing_invoice_no'] = $billing_invoice_no;
                    continue;
                }

                foreach ($invoicePayments as $k1 => $v1) {
                    $billing_invoice_no = $v1['invoice_no'] . ';' . $billing_invoice_no;
                }

                $billing_invoice_no = substr($billing_invoice_no, 0, strlen($billing_invoice_no) - 1);

                $data[$k]['billing_invoice_no'] = $billing_invoice_no;
            }
        }
        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('回款');

        //设置列标题
        $columnTitles = [
            //'发票ID', 
            '客户名称',
            '客户简称',
            '合同编号',
            '关联ERP合同编号',
            '关联会签合同编号',
            '财务编码',
            '合同性质',
            '合同来源（业财）',
            '合同来源（财务）',
            '账套公司',
            '合同签署公司',
            '合同所属区域',
            '实收时间',
            '归档时间',
            '实收编号',
            '实收总额',
            '是否运营关注款项',
            '账号开通时间（第一次）',
            '收款账号',
            '收款账户',
            '付款客户名称',
            '供应商名称',
            '对应发票',
            '业务类型',
            '手续费',
            '实收总额+手续费'
        ];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['payment_id']);
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_contract_code']); //关联ERP合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, ''); //关联会签合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['finance_code']); //财务编码
                $i++;
                $propertyName = ContractPropertyRepository::getPropertyNameByPropertyId($val['contract_property_id']);
                $activeSheet->setCellValue($i . $j, $propertyName === FALSE ? '' : $propertyName); //合同性质
                $i++;
                $activeSheet->setCellValue($i . $j, $val['soure_business']); //合同来源（业财）
                $i++;
                $activeSheet->setCellValue($i . $j, $val['soure_financial']); //合同来源（财务）
                $i++;
                $accountCompayName = ContractAccountCompanyRepository::getContractAccountCompanyListByPropertyId($val['contract_property_id']);
                $activeSheet->setCellValue($i . $j, empty($accountCompayName) ? '' : $accountCompayName[0]->account_company_name); //账套公司
                $i++;
                $activeSheet->setCellValue($i . $j, $val['company_name']); //合同签署公司
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['payment_date'])); //实收时间
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['input_date'])); //归档时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_code']);  //实收编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_amount']);    //实收总额
                $i++;
                $activeSheet->setCellValue($i . $j, $this->getIsGzx($val['payment_id']));    //是否运营关注款项
                $i++;
                $activeSheet->setCellValue($i . $j, $this->getContractFirstRightBeginTime($val['contract_id']));    //账号开通时间（第一次）
                $i++;
                $activeSheet->setCellValue($i . $j, $val['receivables_account']);   //收款账号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['receivables_account_name']);  //收款账户
                $i++;
                $activeSheet->setCellValue($i . $j, $val['payment_account_name']);  //付款客户名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['supplier_name']);  //供应商名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['billing_invoice_no']);    //对应发票
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_name']);    //业务类型
                $i++;
                $activeSheet->setCellValue($i . $j, $val['withdraw_fee']);    //手续费
                $i++;
                $activeSheet->setCellValue($i . $j, $val['allamount']);    //实收总额+手续费

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * @param $objPHPExcel
     * @param null $status
     * @param null $property
     * @param null $keyword
     * @param null $areaId
     * @param null $signPeopleId
     */
    private function exportContractProductKtExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null,$businesstype = null){
        $data = ContractManageRepository::getContractProductKtListForExport($status, $property, $keyword, $areaId, $signPeopleId,$businesstype);
        $erpinterface = new ErpInterfaceService();
        foreach ($data as &$item) {
            $item['DcSjzk'] = '';
            if(!empty($item['stock_out_id'])){
                $authdata  = $erpinterface->GetDeliveryDetail($item['stock_out_id']);
                $products = $authdata['data']->YlInfo->Yl_Tenant[0]->Erp_Products;
                if (!empty($products)) {
                    foreach($products as $p){
                        if($item['application_id'] == $p->Product_Info_Id){
                            $item['DcSjzk'] = $p->DcSjzk;
                        }
                    }
                }
            }
        }
        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('产品开通信息');

        //设置列标题
        $columnTitles = [
            '应用名称',
            '授权时间',
            '开通时间',
            '录入时间',
            '生效时间',
            '授权数量',
            '结算类型',
            '结算比例(%)',
            '当次实际折扣(%)',
            '结算金额',
            '客户简称',
            '签约客户全称',
            '合同性质',
            '合同签署日期',
            '合同签约人',
            '关联ERP合同编号',
            '合同编号',
            '出库单号',
            '签约金额',
            '业务类型',
            '合同所属区域',
            '授权标准'
        ];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['application_name']); //应用名称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['authorize_time']); //授权时间
                $i++;
                $activeSheet->setCellValue($i . $j, !empty($val['kt_date']) ? $val['kt_date'] : $val['authorize_time']); //开通时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['input_date']); //录入时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['effect_date']); //生效时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['authorization_numeric']); //授权数量
                $i++;
                switch ($val['balance_type'])
                {
                    case 0:
                        $balance_type_name = '标准结算';
                        break;
                    case 1:
                        $balance_type_name = '特价结算';
                        break;
                    case 2:
                        $balance_type_name = '明折结算';
                        break;
                    default:
                        $balance_type_name = '';
                }
                $activeSheet->setCellValue($i . $j, $balance_type_name); //结算类型
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_rate']); //结算比例(%)
                $i++;
                $activeSheet->setCellValue($i . $j, $val['DcSjzk']); //当次实际折扣(%)
                $i++;
                $activeSheet->setCellValue($i . $j, $val['balance_amount']); //结算金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //签约客户全称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['property_name']); //合同性质
                $i++;
                $activeSheet->setCellValue($i . $j, $val['sign_date']); //合同签署日期
                $i++;
                $activeSheet->setCellValue($i . $j, $val['UserName']); //合同签约人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_contract_code']); //关联ERP合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['stock_out_code']); //出库单号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['sign_amount']); //签约金额
                $i++;
                $activeSheet->setCellValue($i . $j, $val['business_type_name']); //业务类型
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['LicensingStandards']); //授权标准

                $j++;
            }
        }
    }

    private function getIsGzx($paymentid){
        $data = ContractPaymentRepository::getIsOperationGzx($paymentid);
        if(!empty($data)){
            return $data[0]['isgzx'];
        }
        return '';
    }

    /**
     * 导出合同的签约业绩信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractSignAchievementExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null)
    {
        $data = ContractManageRepository::getContractSignAchievementListForExport($status, $property, $keyword, $areaId, $signPeopleId);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('签约业绩');

        //设置列标题
        $columnTitles = [
            '合同性质',
            '客户名称',
            '客户简称',
            '合同编号',
            '合同所属区域',
            '签约业绩金额',
            '签约时间',
            '业绩归属时间',
            '云链业绩归属人',
            '云链业绩归属部门',
            '云链业绩归属区域',
            'ERP业绩归属人',
            'ERP业绩归属ABU',
            'ERP业绩归属ABU负责人',
            'ERP业绩归属部门经理',
            'ERP业绩归属客户经理',
            'ERP业绩归属部门',
        ];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $erpUserInfo = ErpUserRepository::getUserById($val['erp_achievement_belong']);
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['property_name']); // 合同性质
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['achievement_amount']); // 签约业绩金额
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['sign_date'])); // 签约时间
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['achievement_belong_time'])); // 业绩归属时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['belong_name']); // 业绩归属人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['department_name']); // 云客业绩归属部门
                $i++;
                $activeSheet->setCellValue($i . $j, $val['achievementarea_name']); // 云客业绩归属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_name']); // ERP业绩归属人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_abu']); // 业绩归属abu
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_abu_owner']); // ERP业绩归属ABU负责人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_bu_manager']);//ERP业绩归属部门经理
                $i++;
                $activeSheet->setCellValue($i . $j, $val['manager_name']); // ERP业绩归属客户经理
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_bu']); // ERP业绩归属部门
                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出合同的回款业绩信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractPaymentAchievementExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null)
    {
        $data = ContractManageRepository::getContractPaymentAchievementListForExport($status, $property, $keyword, $areaId, $signPeopleId);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('回款业绩');

        //设置列标题
        $columnTitles = [
            '合同性质',
            '客户名称',
            '客户简称',
            '合同编号',
            '合同所属区域',
            '款项名称',
            '款项小类',
            '回款业绩金额',
            '实收时间',
            '业绩归属时间',
            '云链业绩归属人',
            '云链业绩归属部门',
            '云链业绩归属区域',
            'ERP业绩归属人',
            'ERP业绩归属ABU',
            'ERP业绩归属ABU负责人',
            'ERP业绩归属部门经理',
            'ERP业绩归属客户经理',
            'ERP业绩归属部门',
//            '业绩归属区域', 
//            'ERP客户经理'
        ];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $erpUserInfo = ErpUserRepository::getUserById($val['erp_achievement_belong']);
                $i = 'A';
                $activeSheet->setCellValue($i . $j, $val['property_name']); //合同性质
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['receivable_item_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['money_category_item_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['achievement_amount']);
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['received_time'])); // 实收时间
                $i++;
                $activeSheet->setCellValue($i . $j, DateTimeHelper::getDate($val['achievement_belong_time'])); // 业绩归属时间
                $i++;
                $activeSheet->setCellValue($i . $j, $val['belong_name']); // 业绩归属人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['department_name']); // 云客业绩归属部门
                $i++;
                $activeSheet->setCellValue($i . $j, $val['achievementarea_name']); // 云客业绩归属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_name']); // ERP业绩归属人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_abu']); // 业绩归属abu
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_abu_owner']); // ERP业绩归属ABU负责人
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_bu_manager']);//ERP业绩归属部门经理
                $i++;
                $activeSheet->setCellValue($i . $j, $val['manager_name']); // ERP业绩归属客户经理
                $i++;
                $activeSheet->setCellValue($i . $j, $val['erp_belong_bu']); // ERP业绩归属部门
//                $i++;
//                $activeSheet->setCellValue($i . $j, $val['achievementarea_name']);
//                $i++;
//                $activeSheet->setCellValue($i . $j, $val['manager_name']);

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出合同的文档信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractDocumentExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null)
    {
        $data = ContractManageRepository::getContractDocumentListForExport($status, $property, $keyword, $areaId, $signPeopleId);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('文档');

        //设置列标题
        $columnTitles = ['客户名称', '客户简称', '合同编号', '合同所属区域', '文件类型', '纸质合同归档日期', '纸质合同存放位置', '纸质合同类型', '保管人', '所属文件夹名称'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['document_id']);
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['document_ext_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['pigeonhole_date']));
                $i++;
                $activeSheet->setCellValue($i . $j, $val['document_path']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_document_type']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['keeper_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['document_dir']);

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出违规合同信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractViolatedExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null)
    {
        $data = ContractManageRepository::getContractViolatedListForExport($status, $property, $keyword, $areaId, $signPeopleId);

        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('违规合同');

        //设置列标题
        $columnTitles = ['客户名称', '客户简称', '合同编号', '合同所属区域', '违规责任人', '违规大类', '违规小类', '审批人', '审批意见'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['violated_contract_id']);
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['principal_name']);
                $i++;

                $activeSheet->setCellValue($i . $j, $val['category_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['littler_category_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['approver_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['approve_comment']);

                $j++;
            }
        }

        $activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出特批发票信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractSpecialInvoiceExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null)
    {
        $data = ContractManageRepository::getContractSpecialInvoiceListForExport($status, $property, $keyword, $areaId, $signPeopleId);

        if (isset($data) && count($data) > 0) {
            $CategoryList = [
                1 => '合同未归档',
                2 => '开票金额与合同应收金额不相等',
                3 => '开票名称与签约客户名称不一致',
                4 => '结算款未支付',
                5 => '合同未归档',
                6 => '开票名称与付款名称不一致'
            ];
            foreach ($data as $k => $v) {
                $category = $v['category'];
                $data[$k]['category_name'] = '';
                if (!is_null($category) && isset($CategoryList[$category])) {
                    $data[$k]['category_name'] = $CategoryList[$category];
                    continue;
                }
            }
        }
        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('特批发票');

        //设置列标题
        $columnTitles = ['客户名称', '客户简称', '合同编号', '合同所属区域', '合同签署公司', '开票单位', '发票抬头', '发票号码', '发票日期', '特批类型', '兑现责任人', '承诺日期', '兑现日期'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['special_approval_invoice_id']);
                //$i++;
                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称                                
                $i++;
                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_company_name']); //合同签署公司
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_company_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_customer_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['invoice_no']);
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['invoice_date']));
                $i++;
                $activeSheet->setCellValue($i . $j, $val['category_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['principal_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['promise_fulfil_time']));
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['actual_fulfil_time']));
                $i++;

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    /**
     * 导出特批授权信息
     * @param \PHPExcel $objPHPExcel
     * @param string $status
     * @param string $property
     * @param string $keyword
     * @param string $areaId
     * @param string $signPeopleId
     */
    private function exportContractSpecialAuthorizeExecl($objPHPExcel, $status = null, $property = null, $keyword = null, $areaId = null, $signPeopleId = null)
    {
        $data = ContractManageRepository::getContractSpecialAuthorizeListForExport($status, $property, $keyword, $areaId, $signPeopleId);

        if (isset($data) && count($data) > 0) {
            $CategoryList = [
                1 => '合同未归档',
                2 => '首期款未回',
                3 => '授权信息与合同信息不一致',
                4 => '合同扫描件未提供',
                5 => '结算款未支付',
                6 => '其他',
                7 => '合同未归档,首期款未回'
            ];

            foreach ($data as $k => $v) {
                if (empty($v['contract_id'])) {
                    $applications = [];
                } else {
                    $applications = $this->getContractOrganizationInfo($v['contract_id']);
                }

                $data[$k]['applications'] = $applications;
                $data[$k]['has_applications'] = !empty($v['contract_id']);

                $category = $v['category'];
                $data[$k]['category_name'] = '';
                if (!is_null($category) && isset($CategoryList[$category])) {
                    $data[$k]['category_name'] = $CategoryList[$category];
                }
            }
        }
        //设置当前的sheet
        $activeSheet = self::getActiveSheet($objPHPExcel);
        $activeSheet->setTitle('特批授权');

        //设置列标题
//        $columnTitles = ['客户名称', '客户简称', '合同编号', '合同所属区域', '租户名称', '企业号', '租期开始日期', '租期结束日期', '应用信息', '特批类型', '兑现责任人', '承诺日期', '兑现日期'];
        $columnTitles = ['租户名称', '合同编号', '特批类型', '兑现责任人', '承诺日期', '兑现日期', '备注'];
        $columnIndex = 'A';
        foreach ($columnTitles as $key => $value) {
            $activeSheet->setCellValue($columnIndex . '1', $value);
            $activeSheet->getColumnDimension($columnIndex)->setWidth(20);
            $columnIndex++;
        }

        //设置单元格的值
        if (!empty($data)) {
            $j = 2;
            foreach ($data as $key => $val) {
                $i = 'A';
                //$activeSheet->setCellValue($i . $j, $val['special_approval_authorize_id']);
                //$i++;
//                $activeSheet->setCellValue($i . $j, $val['customer_full_name']); //客户名称
//                $i++;
//                $activeSheet->setCellValue($i . $j, $val['customer_name']); //客户简称
//                $i++;
                $activeSheet->setCellValue($i . $j, $val['organization_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['contract_code']); //合同编号
                $i++;
//                $activeSheet->setCellValue($i . $j, $val['area_name']); //合同所属区域
//                $i++;

//                $activeSheet->setCellValue($i . $j, $val['UniqueName']);
//                $i++;
//                if ($val['has_applications']) {
//                    $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['applications']['beginOn']));
//                }
//                $i++;
//                if ($val['has_applications']) {
//                    $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['applications']['endOn']));
//                }
//                $i++;

//                $appinfo = '';
//                if ($val['has_applications']) {
//                    foreach ($val['applications']['AuthorizeList'] as $key => $value) {
//                        $appinfo .= $value['applicationName'] . '：' . $value['totalNum'] . '（按项目数）' . chr(13) . chr(10);
//                    }
//                }
//                $activeSheet->setCellValue($i . $j, $appinfo);
//                $i++;

                $activeSheet->setCellValue($i . $j, $val['category_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, $val['principal_name']);
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['promise_fulfil_time']));
                $i++;
                $activeSheet->setCellValue($i . $j, self::getDateTimeString($val['actual_fulfil_time']));
                $i++;
                $activeSheet->setCellValue($i . $j, $val['comment']);

                $j++;
            }
        }

        //$activeSheet->getColumnDimension('A')->setVisible(false); //把guid 设置为隐藏列		
    }

    private static function getDateTimeString($value, $format = null)
    {
        if (empty($format)) {
            $format = "Y-m-d";
        }
        if (is_null($value) || empty($value)) {
            return '';
        }

        return date($format, strtotime($value));
    }

    /**
     * @param $userId 收件人id
     * @param $subject 邮件主题
     * @param $template 模板名称：invoiceExpired、invoiceNoContract、receivableExpired、revenue、verify
     * @param $params 模板对应的字段内容
     */
    private function sendEmail($userId, $subject, $template, $params, $cc)
    {
        $user = ErpUserRepository::getUserById($userId);
        if (empty($user)) {
            return;
        }
        //获取抄送人
        $copyToEMail = ContractEmailContactsRepository::getCCContactsByBu($user['BUGUID'], $user['UserCode']);

        $params['ScrmUrl'] = \Yii::$app->params['ScrmUrl'];
        $params['userName'] = $user['UserName'];

        if (is_array($cc)) {
            $copyToEMail = array_merge($copyToEMail, $cc);
        }

        return $this->sendMailHandler([$user['Email'] => $user['UserName']], $subject, $template, $params, $copyToEMail);
    }

    /**
     * @param $userId 收件人id
     * @param $subject 邮件主题
     * @param $template 模板名称：invoiceExpired、invoiceNoContract、receivableExpired、revenue、verify
     * @param $params 模板对应的字段内容
     */
    private function sendEmailForAuthorizeExpired($userId, $subject, $template, $params, $cc)
    {
        $user = ErpUserRepository::getUserById($userId);
        if (empty($user)) {
            return;
        }
        //获取抄送人
        $copyToEMail = ContractEmailContactsRepository::getCCContactsByBu($user['BUGUID'], $user['UserCode']);

        $toEmail = $copyToEMail;
        $params['msg'] = '';
        $hasCc = true;
        //如果没有配置抄送人，则提醒
        if (empty($copyToEMail)) {
            $params['userName'] = '付小玲';
            $toEmail = $cc;
            $params['msg'] = '该公司未设置租期到期提醒责任人，请确认';
            $hasCc = false;
        }

        $params['ScrmUrl'] = \Yii::$app->params['ScrmUrl'];

        if ($hasCc && is_array($cc)) {
            $copyToEMail = array_merge($copyToEMail, $cc);
        }

        return $this->sendMailHandler($toEmail, $subject, $template, $params, $copyToEMail);
    }

    private function sendMailHandler($sendToUser, $subject, $template, $params, $cc)
    {
        $params['ScrmUrl'] = \Yii::$app->params['ScrmUrl'];
        return EmailService::sendEMail($sendToUser, $subject, 'contract/' . $template, $params, $cc);
    }

    /**
     * 根据时间获取合同
     * @param type $beginTime
     * @param type $endTime
     */
    public function getContractListByTime($beginTime, $endTime,$contractid)
    {
        return ContractManageRepository::getContractListByTime($beginTime, $endTime,$contractid);
    }

    /**获取合同返款列表
     * @return array
     */
    public function getContractFkList($contractid)
    {
        return ContractManageRepository::getContractFkList($contractid);
    }

    /**
     * 根据时间获取合同
     * @param $beginTime
     * @param $endTime
     * @return array
     */
    public function getContractListByTimeNoAsFields($beginTime, $endTime)
    {
        return ContractManageRepository::getContractListByTimeNoAsFields($beginTime, $endTime);
    }

    public function getRevenueInfotByTime($beginTime, $endTime)
    {
        return ContractRevenueRepository::getRevenueInfotByTime($beginTime, $endTime);
    }

    private function getUserNameById($userGUID, $default = '')
    {
        if (empty($userGUID)) {
            return $default;
        }

        $name = ErpUserRepository::getUserNameByBuguid($userGUID);
        return empty($name) ? $default : $name;
    }

    private function getBuNameById($buGUID, $default = '')
    {
        if (empty($buGUID)) {
            return $default;
        }

        $name = ErpBusinessUnitRepository::getBunameByBuguid($buGUID);
        return empty($name) ? $default : $name;
    }

    public function getSignAchievementsByTime($beginTime, $endTime)
    {
        return ContractManageRepository::getSignAchievementsByTime($beginTime, $endTime);
    }

    public function getPaymentInfoByTime($beginTime, $endTime,$contractid)
    {
        return ContractManageRepository::getPaymentInfoByTime($beginTime, $endTime,$contractid);
    }

    public function getProductInfoByTime($beginTime, $endTime,$contractid)
    {
        return ContractManageRepository::getProductInfoByTime($beginTime, $endTime,$contractid);
    }

    public function getInvoicesByTime($beginTime, $endTime,$contractid='')
    {
        $invoicesInfo = ContractManageRepository::getInvoicesByTime($beginTime, $endTime,$contractid);
        foreach ($invoicesInfo as &$item) {
            $flag = 0; //正常发票
            if (!empty($item['red_by_invoice_id'])) {
                $flag = 1; //被红冲的发票
            }
            if ($item['is_red_invoice'] == 1) {
                $flag = 2; //红冲的发票
            }
            if ($item['is_receipt'] == 1) {
                $flag = 3; //收据
            }
            unset($item['red_by_invoice_id']);
            unset($item['is_red_invoice']);
            unset($item['is_receipt']);
            $item['ReceiptAttribute'] = $flag;
        }
        return $invoicesInfo;
    }

    public function getInvoicesAbstract(){
        $invoicesAbstract = ContractManageRepository::getInvoicesAbstract();
        return $invoicesAbstract;
    }

    public function getGetOrganizationinfoByTime($beginTime, $endTime)
    {
        $tenant_contract_list = TenantService::getContractsList($beginTime, $endTime);
        $code_list = [];
        $result = [];
        if (!empty($tenant_contract_list)) {
            foreach ($tenant_contract_list as $tenant_contract) {
                $code = $tenant_contract['contract_code'];
                if (!in_array($code, $code_list)) {
                    $code_list[] = $code;
                }
            }

            if (!empty($code_list)) {
                $contract_list = ContractManageRepository::getContractListByCode($code_list);
                $contract_list_temp = [];
                if (!empty($contract_list)) {
                    foreach ($contract_list as $contract) {
                        $code = $contract['contract_code'];
                        if (!array_key_exists($code, $contract_list_temp)) {
                            $contract_list_temp[$code] = $contract;
                        }
                    }

                    foreach ($tenant_contract_list as $tenant_contract) {
                        $code = $tenant_contract['contract_code'];
                        if (array_key_exists($code, $contract_list_temp)) {
                            $contract_temp = $contract_list_temp[$code];
                            $contract = [];
                            $contract['DeliveryGUID'] = $contract_temp['contract_id'];
                            $contract['DeliveryCode'] = $contract_temp['contract_code'];
                            $contract['DeliveryDate'] = $tenant_contract['rental_start'];
                            $contract['EndDate'] = $tenant_contract['rental_end'];
                            $contract['ContractGUID'] = $contract_temp['contract_id'];

                            $result[] = $contract;
                        }
                    }

                }
            }

        }

        return $result;
    }

    public function getInvoicePaymentByTime($beginTime, $endTime,$contractid)
    {
        return ContractManageRepository::getInvoicePaymentByTime($beginTime, $endTime,$contractid);
    }

    public function getReceivableInfoByTime($contractid, $beginTime, $endTime)
    {
        return ContractManageRepository::getReceivableInfoByTime($contractid ,$beginTime, $endTime);
    }

    public function getAllContractApplicationByContractId($contractId)
    {
        return ContractApplicationRepository::getAllContractApplicationByContractId($contractId);
    }

    public function getContractApplicationList($code)
    {
        $list = ContractManageRepository::getContractApplicationList($code);
        if (!empty($list)) {
            $contract_mapping = [];
            foreach ($list as $contract) {
                $contract_id = $contract['contract_id'];
                if (array_key_exists($contract_id, $contract_mapping)) {
                    $data = $contract_mapping[$contract_id];
                    $application_list = $data['application_list'];

                    $application = [];
                    $application['application_id'] = $contract['application_id'];
                    $application['unique_name'] = $contract['unique_name'];
                    $application['application_name'] = $contract['application_name'];
                    $application['unit'] = $contract['unit'];
                    $application['price'] = $contract['price'];
                    $application['num'] = $contract['authorization_numeric'];
                    if (!empty($application['application_id'])) {
                        $application_list[] = $application;
                    }

                    $data['application_list'] = $application_list;
                    $contract_mapping[$contract_id] = $data;
                } else {
                    $data = [];
                    $data['contract_id'] = $contract['contract_id'];
                    $data['contract_code'] = $contract['contract_code'];
                    $data['sign_date'] = $contract['sign_date'];

                    $application = [];
                    $application['application_id'] = $contract['application_id'];
                    $application['unique_name'] = $contract['unique_name'];
                    $application['application_name'] = $contract['application_name'];
                    $application['unit'] = $contract['unit'];
                    $application['price'] = $contract['price'];
                    $application['num'] = $contract['authorization_numeric'];
                    $application_list = [];
                    if (!empty($application['application_id'])) {
                        $application_list[] = $application;
                    }

                    $data['application_list'] = $application_list;
                    $contract_mapping[$contract_id] = $data;
                }
            }
            $result = [];
            foreach ($contract_mapping as $contract) {
                $result[] = $contract;
            }
            return $result;
        }

        return $list;
    }

    public function updateContractApplicationRent($contract)
    {
        $code = $contract->contract_code;
        $is_special_approval = $contract->is_special_approval;
        $entity = '';
        $return = true;
        if(!empty($code)) {
            $entity = ContractManageEntity::find()->where(['contract_code' => $code])->one();
        }
        if($is_special_approval == 1){
            $return = ContractManageRepository::saveSpecialApproval($contract,$entity);
        }
        if (!empty($entity) && $return) {
            $returninfo = ContractManageRepository::updateContractApplicationRent($contract,$entity->contract_id);
            if(!$returninfo){
                $this->setAndReturn(ErrorCode::ERR_SAVE_DATA_FAIL, '', '保存合同产品信息失败');
            }
        }
    }

    public function SetContractTenantRelation($relationinfo){
        $contractcode = $relationinfo->contract_code;
        $tenantid = $relationinfo->tenant_id;
        $systemflag = $relationinfo->system_flag;
        $contract = ContractManageEntity::find()->where(['contract_code'=>$contractcode])->one();
        $contractguid = '';
        if(!empty($contract)){
            $contractguid = $contract->contract_id;
        }
        $relation = ContractTenantRelationEntity::find()
            ->where(['contract_code'=>$contractcode,'tenant_id'=>$tenantid,'system_flag'=>$systemflag])
            ->one();
        //不存在则新增
        if(empty($relation)){
            $newrelation = new ContractTenantRelationEntity();
            $newrelation->tenant_relation_id = StringHelper::uuid();
            $newrelation->contract_code = $contractcode;
            $newrelation->contract_id = $contractguid;
            $newrelation->tenant_id = $tenantid;
            $newrelation->tenant_code = $relationinfo->tenant_code;
            $newrelation->tenant_name = $relationinfo->tenant_name;
            $newrelation->kt_date = $relationinfo->kt_date;
            $newrelation->system_flag = $systemflag;
            if(!$newrelation->save()){
                return $this->setAndReturn(ErrorCode::ERR_SAVE_DATA_FAIL, '', '保存合同租户关系失败');
            }
            return true;
        }
    }

    /**
     * 处理从商机系统传过来的数据，插入合同\应收款\产品信息\收入信息\文档信息
     * @param $contract
     * @param $receivableData
     * @param $productinfos
     * @param $incomeinfos
     * @param $docinfos
     * @return bool
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     */
    public function doInsertFromBusinessSystem($contract, $receivableData,$productinfos,$incomeinfos,$docinfos)
    {
        /** @var ContractReceivableService $contractReceivableService */
        $contractReceivableService = Yii::createObject(ContractReceivableService::className());

        //保存合同，开启事务
        $connection = MyscrmContractEntity::getDb();
        $transaction = $connection->beginTransaction();
        try {
            //保存合同
            $contractId = $this->addContract($contract, [], true);
            if (!$contractId) {
                $transaction->rollBack();
                return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同失败');
            }

            //保存应收款
            foreach ($receivableData as $receivable) {
                $result = $this->addReceivable($contractReceivableService,$receivable);
                if($result === false){
                    $transaction->rollBack();
                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存应收款失败.');
                }
            }

            //保存产品信息
            foreach($productinfos as $product){
                $result = $this->addRroduct($contractId,$product);
                if($result === false){
                    $transaction->rollBack();
                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存产品信息失败.');
                }
            }

            //保存收入信息,收入项信息又业财在saas开通授权后再给
//            foreach($incomeinfos as $incom){
//                $result = $this->addIncom($contractId,$incom);
//                if($result === false){
//                    $transaction->rollBack();
//                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存收入信息失败.');
//                }
//            }

            //保存文档信息
            foreach($docinfos as $doc){
                $result = $this->addDoc($contractId,$doc);
                if($result === false){
                    $transaction->rollBack();
                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存文档信息失败.');
                }
            }

            $transaction->commit();
            return true;

        } catch (\Exception $ex) {
            $transaction->rollBack();
            Yii::error((string)$ex);
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同失败:' . $ex->getMessage());
        }
    }

    private function addReceivable($contractReceivableService,$receivable){
        $receivableArr = [];
        $receivableArr['contract_id'] = $receivable['contract_id']; //合同ID
        $receivableArr['receivable_id'] = $receivable['receivable_id']; //应收款GUID

        //传过来的是文字，需要转换为ID
        $receivable_item_name = $receivable['receivable_item_name']; //款项名称
        $money_category_item_name = $receivable['money_category_item_name']; //款项小类
        $receivableArr['receivable_item_id'] = $this->getReceivableItemIdByItemName($receivable_item_name);
        $receivableArr['money_category_item_id'] = $this->getMoneyCategoryItemIdByItemName($money_category_item_name);
        $receivableArr['payment_condition'] = $receivable['payment_condition']; //付款条件
        $receivableArr['receivable_amount'] = $receivable['receivable_amount']; //应收金额
        $receivableArr['receivable_date'] = $receivable['receivable_date']; //应收日期
        $receivableArr['payee_id'] = $receivable['unite_sales_id']; //由于商机系统那边没有此字段，故默认为“租用服务收入项”
        $receivableArr['revenue_type'] = $this->getRevenueTypeIdByName($receivable['income_type']);//核算收入类别
        $receivableArr['remark'] =  $receivable['remark'];//备注

        if ($receivable['receivable_type'] == '新签') {
            $receivableArr['contract_property'] = 0;
        } else {
            $receivableArr['contract_property'] = 1;
        }

        $contractReceivableModel = new ContractReceivableModel(['scenario' => 'savecontractreceivable']);
        if ($contractReceivableModel->load($receivableArr, '')) {
            $result = $contractReceivableService->saveContractReceivable($contractReceivableModel, true);
            if ($result === false) {
                return false;
            }
        } else {
            return false;
        }
    }

    private function addRroduct($contractId,$product){
        $contractapp = new ContractApplicationEntity();
        $contractapp->contract_application_id = StringHelper::uuid();
        $contractapp->application_id = $product['product_id'];
        //自己计算产品总价
        $amount = 0;
        $price = 0;
        $appinfo = ApplicationInfoRepository::getApplicationInfoById($product['product_id']);
        if(!empty($appinfo)){
            $price = empty($appinfo->BenchmarkPrice)?0:$appinfo->BenchmarkPrice;
            $amount = (empty($appinfo->BenchmarkPrice)?0:$appinfo->BenchmarkPrice) * (empty($product['number'])?0:$product['number']);
        }
        $contractapp->price = $price;
        $contractapp->amount = $amount;
        $contractapp->contract_id = $contractId;
        $contractapp->unit = $product['licens_standards'];
        $contractapp->authorization_numeric = $product['number'];
        $contractapp->rent_period = empty($product['rent_time']?null:$product['rent_time']);
        if(empty($product['contract_type'])) {
            $contract_type = null;
        } elseif ($product['contract_type'] == '新增') {
            $contract_type = 1;
        } elseif ($product['contract_type'] == '续签') {
            $contract_type = 2;
        } else {
            $contract_type = $product['contract_type'];
        }
        //$contractapp->contract_type = empty($product['contract_type']?null:$product['contract_type']);
        $contractapp->contract_type = $contract_type;
        return $contractapp->save();
    }

    private function addIncom($contractId,$incom){
        $manageEntity = ContractManageRepository::getContractManageModelByContractId($item['contract_id']);
        $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
        $num = $manageEntity->inc;
        $num < 10 && $num = "0" . $num;
        $incomecode = $manageEntity->contract_code . "-SR-" . $num; // 生成收入项编码

        $contractrev = new ContractRevenueEntity();
        $contractrev->revenue_id = StringHelper::uuid();
        $contractrev->income_code = $incomecode;
        $contractrev->contract_id=$contractId;
        $contractrev->amount = $incom['income_money'];
        $contractrev->revenue_type = $this->getRevenueTypeIdByName($incom['income_type']);
        $manageEntity->save();
        return $contractrev->save();
    }

    private function addDoc($contractId,$doc){
        $contractdoc = new DocumentEntity();
        $contractdoc->document_id = StringHelper::uuid();
        $contractdoc->business_id = $contractId;
        $contractdoc->document_name = $doc['doc_name'];
        $contractdoc->document_ext_name = $doc['doc_type'];
        $contractdoc->document_path = $doc['doc_url'];
        $contractdoc->modified_on = $doc['modify_time'];
        $contractdoc->created_by = 'interface';
        return $contractdoc->save();
    }

    private function getRevenueTypeIdByName($typename){
        return BussAccountTypesRepository::getRevenueTypeIdByName($typename);
    }

    /**
     * 根据款项名称,获取款项id
     * @param string $receivableItemName 款项名称
     * @return string 款项名称
     */
    public function getReceivableItemIdByItemName($receivableItemName)
    {
        return ReceivableItemRepository::getReceivableItemIdByItemName($receivableItemName);
    }

    /**
     * 根据id,获取名称
     * @param string $moneyCategoryItemName 名称
     * @return string 名称
     */
    public function getMoneyCategoryItemIdByItemName($moneyCategoryItemName)
    {
        return MoneyCategoryItemRepository::getMoneyCategoryItemIdByItemName($moneyCategoryItemName);
    }

    /**
     * 根据合同ID获取对应的应收款项明细
     * @param string $contractId 合同id
     * @param boolean $withBadDebt 是否包含坏账
     * @return array
     */
    public function getReceivableInfoByContractId($contractId, $withBadDebt = true)
    {
        return ContractReceivableRepository::getReceivableInfoByContractId($contractId, $withBadDebt);
    }

    /**
     * 获取支付列表信息
     * @param $params
     *
     * @return array
     */
    public function getPayinfoLists($params)
    {
        $pageParam = new PageParam($params['pageIndex'], $params['pageSize'], '', '');
        $data = ContractPayinfoRepository::getPayinfoLists($pageParam, $params);

        if (empty($data)) {
            return [];
        }

        foreach ($data['items'] as &$record) {
            $record['contract_code'] = '';
            if (empty($record['contract_id'])) {
                continue;
            }
            // 获取合同业务类型,合同编号
            $contract_info = ContractManageRepository::getContractInfoByContractid($record['contract_id']);

            if (empty($contract_info)) {
                continue;
            }

            $record['contract_code'] = $contract_info['contract_code'];

            //获取合同类型名称,前段作为参数使用
            $businessTypeInfo = ContractBusinessTypeRepository::getBusinessTypeById($contract_info['business_type_id']);
            $record['business_type_name'] = empty($businessTypeInfo['business_type_name'])?'':$businessTypeInfo['business_type_name'];
        }

        foreach ($data['itemsAll'] as &$record) {
            $record['contract_code'] = '';
            if (empty($record['contract_id'])) {
                continue;
            }
            // 获取合同业务类型,合同编号
            $contract_info = ContractManageRepository::getContractInfoByContractid($record['contract_id']);

            if (empty($contract_info)) {
                continue;
            }

            $record['contract_code'] = $contract_info['contract_code'];

            //获取合同类型名称,前段作为参数使用
            $businessTypeInfo = ContractBusinessTypeRepository::getBusinessTypeById($contract_info['business_type_id']);
            $record['business_type_name'] = empty($businessTypeInfo['business_type_name'])?'':$businessTypeInfo['business_type_name'];
        }

        return $data;
    }

    /**
     * 获取供应商列表
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getContractSuppliers()
    {
        return ContractSupplierRepository::getSupplierNameLists();
    }

    /**
     * 根据提供商名字获取提供商信息
     * @param string $supplier_name
     *
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getSupplierInfoByName($supplier_name = '')
    {
        return ContractSupplierRepository::getSupplierInfoByName($supplier_name);
    }

    public function getBusinessTypeInfoByName($business_type = '')
    {
        return ContractBusinessTypeRepository::getBusinessTypeByName($business_type);
    }

    public function getBusinessTypeAll(){
        return ContractBusinessTypeRepository::getBusinessTypeAll();
    }

    /**
     * 导入发票信息
     * @return array|bool
     */
    public function importInvoiceListExecl($contract_id = '')
    {
        if (empty($contract_id)) {
            return $this->setAndReturn(-1, '', '合同不能为空');
        }

        if (empty($_FILES ['file'])) {
            return $this->setAndReturn(-1, '', '上传文件不能为空');
        }
        $filename = explode('.', $_FILES ['file']['name']);
        if ($filename [1] != 'xls' && $filename [1] != 'xlsx') {
            return $this->setAndReturn(-1, '', '请上传EXCEL文件');
        }

        $import_data = ExcelManage::importDataByFilePath($_FILES['file']['tmp_name'], 2);

        if (empty($import_data)) {
            return $this->setAndReturn(-1, '', 'EXCEL文件无数据');
        }

        $invoice_data = [];
        $invoice_codes = [];
        foreach ($import_data as $data) {
            $data = implode(',', $data);
            $import = [
                'contract_id' => $contract_id,
            ];
            list(
                $index,
                $import['invoice_category'],
                $import['invoice_code'],
                $import['invoice_type'],
                $import['invoice_no'],
                $import['proposer_name'],// 申请人id
                $import['customer_name'],
                $import['invoice_company_name'],
                $import['invoice_amount'],
                $import['invoice_date']) = \explode(',', $data);

            $import['invoice_category'] = \Yii::$app->params['invoice_category'][$import['invoice_category']];
            if(empty($import['invoice_type'])){
                $import['invoice_type'] = '0';
            }else {
                $import['invoice_type'] = \Yii::$app->params['invoice_type'][$import['invoice_type']];
            }
            $import['invoice_id'] = StringHelper::uuid();
            $import['invoice_date'] = date('Y-m-d H:i:s', PHPExcel_Shared_Date::ExcelToPHP($import['invoice_date']));
            $import['invoice_amount'] = empty($import['invoice_amount'])?0:$import['invoice_amount'];

            $import['proposer_id'] = ErpUserRepository::getUserGUIDByUserName($import['proposer_name']);
            $import['invoice_company_id'] = InvoiceBusinessUnitRepository::getInvoiceBusinessUnitByBUName($import['invoice_company_name'])['BUGUID'];

            if (empty($import['invoice_company_id'])) {
                $message = '导入的excel文件中的开票单位 "'. $import['invoice_company_name'] . '" 有误,请检查';
                return $this->setAndReturn(-1, $message, $message);
            }

            unset($import['proposer_name'], $import['invoice_company_name']);

            $invoice_data[] = $import;
            // 发票代码合集
            $invoice_codes[] = empty($import['invoice_code'])?'':$import['invoice_code'];
        }

        if (empty($invoice_data)) {
            return $this->setAndReturn(-1, '', 'EXCEL文件无数据');
        }

        // del
        InvoiceRepository::delInvoiceBatch($invoice_codes);

        // insert into db
        $result = InvoiceRepository::addInvoiceBatch($invoice_data);

        return $result;
    }

    /**
     * 导入开发商线下活动收款信息
     * @return array|bool
     */
    public function importSupplierPaymentListExecl($contract_id = '')
    {
        if (empty($_FILES ['file'])) {
            return $this->setAndReturn(-1, '', '上传文件不能为空');
        }
        $filename = explode('.', $_FILES ['file']['name']);
        if ($filename [1] != 'xls' && $filename [1] != 'xlsx') {
            return $this->setAndReturn(-1, '', '请上传EXCEL文件');
        }

        $import_data = ExcelManage::importDataByFilePath($_FILES['file']['tmp_name'], 2);

        $income_data = [];
        foreach ($import_data as $data) {
            $data = implode(',', $data);
            $import = [
                'contract_id' => $contract_id
            ];

            list(
                $index,
                $import['username'],
                $import['company_name'],
                $import['is_auth'],
                $import['is_gloden'],
                $import['payamount'],
                $import['deduction'],
                $import['deduction_orderid'],
                $import['payway'],
                $import['sign_up_time'],
                $import['invoice_code']
                ) = explode(',', $data);

            // 新增判断
            if (empty($import['username']) || empty($import['company_name'])) {
                continue;
            }

            $import['is_auth'] = $import['is_auth'] == '是' ? 1 : 0;
            $import['is_gloden'] = $import['is_gloden'] == '是' ? 1 : 0;
            $import['deduction'] = (empty($import['deduction']) || !is_numeric($import['deduction'])) ? '0.00' : $import['deduction'];
            $import['payamount'] = (empty($import['payamount']) || !is_numeric($import['payamount'])) ? '0.00' : $import['payamount'];
            $import['sign_up_time'] = date('Y-m-d H:i:s', PHPExcel_Shared_Date::ExcelToPHP($import['sign_up_time']));

            $income_data[] = $import;
        }

        $result = ContractSuppliersPaymentEntity::deleteAll(['contract_id'=>$contract_id]);
        // insert into db
        $result = ContractSuppliersPaymentRepository::addPaymentBatch($income_data);

        return $result;
    }

    /**
     * 保存交付信息
     * @param $editmode     编辑模式
     * @param $oid      主键
     * @param $applicationname
     * @param $begintime
     * @param $endtime
     */
    public function savePayoverinfo($editmode,$oid,$contractid,$contractcode,$applicationname,$begintime,$endtime)
    {
        if ($editmode == '1') {
            $payover = new ContractPayoverEntity();
            $payover->contract_payover_id = StringHelper::uuid();
            $payover->contract_id = $contractid;
            $payover->contract_code = $contractcode;
            $payover->application_name = $applicationname;
            $payover->begin_time = $begintime;
            $payover->end_time = $endtime;
            if(!$payover->save()){
                return false;
            }
        }else{
            $payover = ContractPayoverEntity::find()->where(['contract_payover_id'=>$oid])->one();
            $payover->application_name = $applicationname;
            $payover->begin_time = $begintime;
            $payover->end_time = $endtime;
            if(!$payover->save()){
                return false;
            }
        };
        //更新应收信息
        $this->updateIncomes($payover);
        return true;
    }

    public function savePayoverSaasInfo($oid,$tenantname,$tenantcode,$authorizeperiod)
    {
        $payover = ContractPayoverEntity::find()->where(['contract_payover_id'=>$oid])->one();
        $payover->tenant_name = $tenantname;
        $payover->tenant_code = $tenantcode;
        $payover->authorize_period = $authorizeperiod;
        if(!$payover->save()){
            return false;
        }
        return true;
    }

    //根据结算数据生成收入信息
    private function updateIncomes($item){
        $payovers = ContractPayoverEntity::find()
            ->where(['contract_id'=>$item->contract_id])
            ->all();
        $isHaveCarryover = ContractRevenueRepository::isHaveCarryover($item->contract_id,$item->contract_payover_id);
        //已结转的不支持重复执行
        if($isHaveCarryover){
            return;
        }

        $newincome = ContractRevenueEntity::find()->where(['contract_id'=>$item->contract_id,'contract_payover_id'=>$item->contract_payover_id])->one();
        $before = $newincome?$newincome->getAttributes():false;
        $manageEntity = ContractManageRepository::getContractManageModelByContractId($item->contract_id);
        if(empty($newincome)) {
            $manageEntity->inc = $manageEntity->inc == 0 ? 1 : ++$manageEntity->inc;
            $num = $manageEntity->inc;
            $num < 10 && $num = "0" . $num;
            $incomecode = $manageEntity->contract_code . "-SR-" . $num; // 生成收入项编码

            $newincome = new ContractRevenueEntity();
            $newincome->revenue_id = StringHelper::uuid();
            $newincome->contract_id = $item->contract_id;
            $newincome->contract_payover_id = $item->contract_payover_id;
            $newincome->income_code = $incomecode;
            $newincome->created_on = ConfigEntity::getDbNowDate();
        }
        $newincome->revenue_type = $this->getBussAccountTypesId($manageEntity->business_type_id,$item->application_name);
        if($manageEntity->business_type_id=='f8592797-54ca-11e7-9f96-000c29310f8b') {
            $newincome->amount = $manageEntity->balance_amount;
            $newincome->wait_confirm_amount = $manageEntity->balance_amount;
        }else{
            $newincome->amount = $manageEntity->sign_amount;
            $newincome->wait_confirm_amount = $manageEntity->sign_amount;
        }
        $newincome->carryover_begin_time = $item->begin_time;
        $newincome->right_begin_time = $item->begin_time;
        $newincome->right_end_time = $item->end_time;
        $newincome->modified_on = ConfigEntity::getDbNowDate();
        $newincome->remark = '交付信息界面保存数据时同步生成';
        $now = $newincome?$newincome->getAttributes():false;
        $res = $newincome->save();
        if(empty($before)){
            IncomeItemLogRepository::add($before,$now,$res,IncomeItemLogRepository::OPERATE_ADD);
        }else{
            IncomeItemLogRepository::add($before,$now,$res,IncomeItemLogRepository::OPERATE_EDIT);
        }
        $manageEntity->save();
    }

    /**
     * @param $editmode
     * @param $oid
     * @param $balancetype
     * @param $balancerate
     * @param $balanceamount
     * @return bool
     */
    public function savePayoverBalanceinfo($banlancedata)
    {
        $balanceamount = $banlancedata['balanceamount'];
        if(empty($banlancedata['oid'])){
            $payover = new ContractPayoverEntity();
            $payover->contract_payover_id = StringHelper::uuid();
            $payover->shipment_status = 0;
            $payover->contract_id = $banlancedata['contractid'];
            $payover->contract_code = $banlancedata['contractcode'];
            $payover->amount = empty($balanceamount)?0:$balanceamount;
            $payover->created_on = ConfigEntity::getDbNowDate();
            $payover->system_flag = 'sys_add';
            $payover->remark = '本系统新增';
        }else {
            $payover = ContractPayoverEntity::find()->where(['contract_payover_id' => $banlancedata['oid']])->one();
            $payover->edit_mode = 0;
            if($payover->balance_amount != $balanceamount){
                $payover->shipment_status = 0;
            }
            $payover->modified_on = ConfigEntity::getDbNowDate();
        }
        $payover->application_id = $banlancedata['applicationid'];
        $payover->application_name = ApplicationInfoRepository::getApplicationInfoById($banlancedata['applicationid'])['application_name'];
        $payover->authorize_time = $banlancedata['authorizetime'];
        $payover->authorization_numeric = $banlancedata['authorizationnumeric'];
        $payover->balance_type = $banlancedata['balancetype'];
        $payover->balance_rate = empty($banlancedata['balancerate'])?0:$banlancedata['balancerate'];
        $payover->balance_amount = $balanceamount;
        $payover->stock_out_code = $banlancedata['stock_out_code'];
        $payover->authorize_period = $banlancedata['authorize_period'];
        if($payover->save()){
            return true;
        }else{
            return false;
        }
    }

    public function deletePayoverinfo($oid,$contractid){
        $ishavecarryover = ContractRevenueRepository::isHaveCarryover($contractid,$oid);

        if($ishavecarryover){
            return false;
        }
        if(ContractRevenueRepository::deleteRevenueByCP($contractid,$oid)) {
            $payover = ContractPayoverEntity::find()->where(['contract_payover_id' => $oid])->one();
            if ($payover->delete()) {
                return true;
            } else {
                return false;
            }
            return false;
        }
    }

    public function searchSuppliersByKey($keyword){
        $suppliers = ContractSupplierEntity::find()
            ->filterWhere(['like','company_name',$keyword])
            ->orFilterWhere(['like','short_name',$keyword])
            ->orFilterWhere(['like','supplier_id',$keyword])
            ->limit(100)
            ->all();
        return $suppliers;
    }

    /**
     * 保存直属会签的草稿合同
     * @param $contract
     */
    public function saveContractDraft($contract,$productData,$docData){
        $sourcecontractid = $contract['contract_id'];
        $newcontractid = StringHelper::uuid();
        $isnew = false;
        $newcontract = ContractManageEntity::find()->where(['erp_contract_id'=>$sourcecontractid])->one();
        if(empty($newcontract)) {
            $isnew = true;
            $newcontract = new ContractManageEntity();
        }
        if($isnew) {
            $newcontract->contract_id = $newcontractid;
            $newcontract->contract_code = ContractFlowCodeRepository::getContractCode();
            $newcontract->business_type_id = 'f85b3855-54ca-11e7-9f96-000c29310f8b';
            $newcontract->input_date = date("Y-m-d H:i:s", ConfigEntity::getDbNowTimestamp());
            $newcontract->erp_contract_code = $contract['contract_code'];
            $newcontract->erp_contract_id = $sourcecontractid;
            $newcontract->sign_amount = $contract['sign_amount'];
            $newcontract->sign_people_id = $contract['sign_people_id'];
            $newcontract->customer_id = $contract['customer_id'];
            $newcontract->customer_name = $contract['customer_name'];
            $newcontract->top_customer_name = $contract['top_customer_name'];
            $newcontract->customer_full_name = $contract['customer_full_name'];
            $newcontract->sign_date = $contract['sign_date'];
            $newcontract->customer_code = $contract['customer_code'];
            $newcontract->contract_property_id = ContractPropertyRepository::getPropertyIdByName($contract['contract_nature']);
            $newcontract->company_id = ContractCompanyRepository::getContractIdByName($contract['sign_buname']);
            $newcontract->input_date = $contract['contract_entry_date'];
            $newcontract->effect_date = $contract['contract_effective_date'];
            $newcontract->rent_amount = $contract['rentdeal_price'];
            $newcontract->delivery_amount = $contract['deliverdeal_price'];
            $newcontract->balance_should_amount = $contract['js_amount'];
            $newcontract->soure_business = '直属会签草稿合同';
        }else{
            $newcontractid = $newcontract->contract_id;
        }
        $erpInterfaceService = Yii::createObject(ErpInterfaceService::className());
        $signUserData = $erpInterfaceService->getUserInfoById($contract['sign_people_id']);
        $newcontract->area_id = $signUserData['BUGUID'];
        $newcontract->sign_people_department_id = $signUserData['DepartmentGUID'];
        $newcontract->sign_people_department_by = $signUserData['DepartmentName'];
        if($newcontract->save()){
            $products = $productData;
            ContractApplicationEntity::deleteAll(['contract_id'=>$newcontractid]);
            foreach($products as $product){
                $contractapp = new ContractApplicationEntity();
                $contractapp->contract_application_id = StringHelper::uuid();
                $contractapp->application_id = $product->product_id;
                //自己计算产品总价
                $amount = 0;
                $price = 0;
                $appinfo = ApplicationInfoRepository::getApplicationInfoById($product->product_id);
                if(!empty($appinfo)){
                    $price = empty($appinfo->BenchmarkPrice)?0:$appinfo->BenchmarkPrice;
                    $amount = (empty($appinfo->BenchmarkPrice)?0:$appinfo->BenchmarkPrice) * (empty($product->number)?0:$product->number);
                }
                $contractapp->price = $price;
                $contractapp->amount = $amount;
                $contractapp->contract_id = $newcontractid;
                $contractapp->unit = $product->licens_standards;
                $contractapp->authorization_numeric = $product->number;
                if(!$contractapp->save()){
                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存产品信息失败.');
                }
            };
            if($isnew) {
                $docs = $docData;
                foreach ($docs as $doc) {
                    $contractdoc = new DocumentEntity();
                    $contractdoc->document_id = StringHelper::uuid();
                    $contractdoc->business_id = $newcontractid;
                    $contractdoc->document_name = $doc->doc_name;
                    $contractdoc->document_ext_name = $doc->doc_type;
                    $contractdoc->document_path = $doc->doc_url;
                    $contractdoc->modified_on = $doc->modify_time;
                    $contractdoc->created_by = 'interface';

                    if (!$contractdoc->save()) {
                        return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存产品信息失败.');
                    }
                }
            }
        }else{
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存失败.');
        }
    }

    /**
     * 保存联营会签的草稿合同
     * @param $contract
     */
    public function saveLinkContractDraft($contract,$productData,$docData){
        $sourcecontractid = $contract['contract_id'];
        $newcontractid = StringHelper::uuid();
        $isnew = false;
        $newcontract = ContractManageEntity::find()->where(['erp_contract_id'=>$sourcecontractid])->one();
        if(empty($newcontract)) {
            $isnew = true;
            $newcontract = new ContractManageEntity();
        }
        if($isnew) {
            $newcontract->contract_id = $newcontractid;
            $newcontract->contract_code = ContractFlowCodeRepository::getContractCode();
            $newcontract->business_type_id = 'f85b3855-54ca-11e7-9f96-000c29310f8b';
            $newcontract->created_on = date("Y-m-d H:i:s", ConfigEntity::getDbNowTimestamp());
            $newcontract->created_by = '接口同步';
            $newcontract->erp_contract_code = $contract['contract_code'];
            $newcontract->erp_contract_id = $sourcecontractid;
            $newcontract->sign_amount = $contract['sign_amount'];
            $newcontract->sign_people_id = $contract['sign_people_id'];
            $newcontract->customer_id = $contract['customer_id'];
            $newcontract->customer_name = $contract['customer_name'];
            $newcontract->top_customer_name = $contract['top_customer_name'];
            $newcontract->customer_full_name = $contract['customer_full_name'];
            $newcontract->sign_date = $contract['sign_date'];
            $newcontract->customer_code = $contract['customer_code'];
            $newcontract->contract_property_id = ContractPropertyRepository::getPropertyIdByName($contract['contract_nature']);
            $newcontract->company_id = ContractCompanyRepository::getContractIdByName($contract['sign_buname']);
            $newcontract->input_date = $contract['contract_entry_date'];
            $newcontract->effect_date = $contract['contract_effective_date'];
            $newcontract->area_id = $contract['contract_buguid'];
            $newcontract->sign_people_department_id = $contract['sign_people_department_id'];
            $newcontract->rent_amount = $contract['rentdeal_price'];
            $newcontract->delivery_amount = $contract['deliverdeal_price'];
            $newcontract->balance_should_amount = $contract['js_amount'];
            $newcontract->soure_business = '联营会签草稿合同';
        }else{
            $newcontractid = $newcontract->contract_id;
        }
        $erpInterfaceService = Yii::createObject(ErpInterfaceService::className());
        $signUserData = $erpInterfaceService->getUserInfoById($contract['sign_people_id']);
        $newcontract->area_id = $signUserData['BUGUID'];
        $newcontract->sign_people_department_id = $signUserData['DepartmentGUID'];
        $newcontract->sign_people_department_by = $signUserData['DepartmentName'];
        if($newcontract->save()){
            $products = $productData;
            ContractApplicationEntity::deleteAll(['contract_id'=>$newcontractid]);
            foreach($products as $product){
                $contractapp = new ContractApplicationEntity();
                $contractapp->contract_application_id = StringHelper::uuid();
                $contractapp->application_id = $product->product_id;
                //自己计算产品总价
                $amount = 0;
                $price = 0;
                $appinfo = ApplicationInfoRepository::getApplicationInfoById($product->product_id);
                if(!empty($appinfo)){
                    $price = empty($appinfo->BenchmarkPrice)?0:$appinfo->BenchmarkPrice;
                    $amount = (empty($appinfo->BenchmarkPrice)?0:$appinfo->BenchmarkPrice) * (empty($product->number)?0:$product->number);
                }
                $contractapp->price = $price;
                $contractapp->amount = $amount;
                $contractapp->contract_id = $newcontractid;
                $contractapp->unit = $product->licens_standards;
                $contractapp->authorization_numeric = $product->number;
                if(!$contractapp->save()){
                    return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存产品信息失败.');
                }
            };
            if($isnew) {
                $docs = $docData;
                foreach ($docs as $doc) {
                    $contractdoc = new DocumentEntity();
                    $contractdoc->document_id = StringHelper::uuid();
                    $contractdoc->business_id = $newcontractid;
                    $contractdoc->document_name = $doc->doc_name;
                    $contractdoc->document_ext_name = $doc->doc_type;
                    $contractdoc->document_path = $doc->doc_url;
                    $contractdoc->modified_on = $doc->modify_time;
                    $contractdoc->created_by = 'interface';

                    if (!$contractdoc->save()) {
                        return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存产品文档失败.');
                    }
                }
            }
            return $newcontractid;
        }else{
            return $this->setAndReturn(ErrorCode::ERR_CONTRACT_ADD, '', '新增合同时保存失败.');
        }
    }

    public function setOverStatusContract($contractid,$overstatus){
        $manageEntity = ContractManageRepository::getContractManageModelByContractId($contractid);
        if(!empty($manageEntity)){
            $manageEntity->isover = $overstatus;
            if($manageEntity->save()){
                return true;
            }
        }
        return false;
    }

    public function saveContractSuppliersPayment($paymentInfo){
        if($paymentInfo['editMode'] == 1){
            $payment = new ContractSuppliersPaymentEntity();
        }else{
            $payment = ContractSuppliersPaymentEntity::find()->where(['id'=>$paymentInfo['id']])->one();
        }
        $payment->contract_id = $paymentInfo['contract_id'];
        $payment->username = $paymentInfo['username'];
        $payment->company_name = $paymentInfo['company_name'];
        $payment->is_auth = empty($paymentInfo['is_auth'])?0:$paymentInfo['is_auth'];
        $payment->is_gloden = empty($paymentInfo['is_gloden'])?0:$paymentInfo['is_gloden'];
        $payment->payamount = empty($paymentInfo['payamount'])?0:$paymentInfo['payamount'];
        $payment->deduction = empty($paymentInfo['deduction'])?0:$paymentInfo['deduction'];
        $payment->deduction_orderid = $paymentInfo['deduction_orderid'];
        $payment->payway = $paymentInfo['payway'];
        $payment->sign_up_time = empty($paymentInfo['sign_up_time'])?null:$paymentInfo['sign_up_time'];
        $payment->invoice_code = $paymentInfo['invoice_code'];
        return $payment->save();
    }

    /**
     * 保存返款记录
     */
    public function saveContractBackAmount($backrecord,$contractid){
        if(empty($backrecord['back_amount_id'])){
            $backinfo = new ContractBackAmountEntity();
            $backinfo->back_amount_id = StringHelper::uuid();
            $backinfo->contract_id = $contractid;
            $backinfo->created_on = ConfigEntity::getDbNowDate();
            $backinfo->created_by = Yii::$app->user->getIdentity()->userguid;
        }else{
            $backinfo = ContractBackAmountEntity::find()->where(['back_amount_id'=>$backrecord['back_amount_id']])->one();
        }
        $backinfo->area_id = $backrecord['area_id'];
        $backinfo->back_amount = $backrecord['back_amount'];
        $backinfo->back_date = empty($backrecord['back_date'])?null:$backrecord['back_date'];
        $backinfo->is_received_invoce = empty($backrecord['is_received_invoce'])?'0':$backrecord['is_received_invoce'];
        $backinfo->invoice_code = empty($backrecord['invoice_code'])?'':$backrecord['invoice_code'];
        $backinfo->remark = empty($backrecord['remark'])?'':$backrecord['remark'];
        $backinfo->modified_on = ConfigEntity::getDbNowDate();
        $backinfo->modified_by = Yii::$app->user->getIdentity()->userguid;
        return $backinfo->save();
    }

    public function deleteContractBackAmount($backamountid,$contractid){
        return ContractBackAmountEntity::find()->where(['back_amount_id'=>$backamountid,'contract_id'=>$contractid])->one()->delete();
    }


    /**
     * 标的物同步至合同系统
     * @param $documents
     * @return bool
     * @throws \yii\db\Exception
     */
    public function doSyncDocument($documents){
        $connection = DocumentEntity::getDb();
        $transaction = $connection->beginTransaction();
        try{
            foreach ($documents as $doc){
                $results[] = DocumentRepository::addDocumentForm($doc,1);
            }
            if(in_array(false, $results)){
                return $this->setAndReturn(__LINE__, '', '同步失败');
            }else{
                $transaction->commit();
                return true;
            }
        }catch (\Exception $ex){
            $transaction->rollBack();
            Yii::error('标的物同步至合同系统接口保存失败：' . (string)$ex);
            return $this->setAndReturn(__LINE__,  '','同步失败');
        }
    }

    /**
     * 获取订单信息
     * @param $contractguid
     * @return array
     */
    public function getOrdersInfo($contractguid,$beginTime,$endTime){
        $orders = ContractManageRepository::getContractOrderInfo($contractguid,$beginTime,$endTime);
        foreach ($orders as $key => $item){
            $orders[$key]['RentEnd'] = $orders[$key]['end_time'];
            $orders[$key]['RentStart'] = $orders[$key]['begin_time'];
            $orders[$key]['RentPeriod'] = intval($orders[$key]['RentPeriod']);
            unset($orders[$key]['end_time']);
            unset($orders[$key]['begin_time']);
        }
        return $orders;
    }
}
